php - 如何通过急切加载返回一个雄辩的多对多关系实例?
问题描述
class Parent extends Model
{
public function kids()
{
return $this->belongsToMany('App\Models\Kid')
->orderBy('age')
->withTimestamps();
}
public function oldestKid()
{
return $this->belongsToMany('App\Models\Kid')
->orderByDesc('age')
->take(1);
}
}
这种方法的问题是$parent->oldestKid
返回一个数组。如果它返回一个对象会感觉更合乎逻辑。
$parent = App\Models\Parent::with('oldestKid')->first();
解决方案
这就是我们最终得到的结果,以及它的工作原理。
重要补充:数据透视表是kid_parent
public function oldestKid()
{
return $this->belongsTo(Kid::class, 'oldest_kid_id', 'id');
}
public function scopeWithOldestKid($query)
{
$query->addSelect(['oldest_kid_id' => KidParent::select('kid_id')
->whereColumn('parent_id', 'parents.id')
->join('kids', 'kids.id', '=', 'kid_parent.kid_id')
->orderByDesc('kids.age')
->take(1)
])->with('oldestKid');
}
那么你可以这样使用它:
$parents = Parent::withOldestKid()->get();
foreach($parents as $parent){
$oldest_kid = $parent->oldestKid;
}
如果你想发疯:你可以使用https://laravel.com/docs/8.x/eloquent#global-scopes所以如果你去找父母,它总是会被加载。
推荐阅读
- swift - RxSwift:如何将简单的观察者添加到 int 值
- php - 在 echo 中包含 php 代码
- angular - 样式绑定和类绑定
- apache - 使用 apache camel 从 http 位置下载
- postgresql - 无法从 Azure 资源连接到用于 postgres 服务器的 Azure 数据库
- jquery - 网页加载时没有填充谷歌表格
- powershell - Inno Setup - 以变量为参数的编译后批处理文件 - 参数未转换为变量的值
- c# - 使用ninject绑定同一接口的不同实现
- javascript - 在 typescript Excel 插件中使用 webworkers
- c# - Xamarin Forms - 滚动到 ScrollView 顶部的按钮