我会知道当您使用带有 Eloquent 的 with
方法检索关系时是否可以为表提供别名?
例如:
Post::where('title', 'like', '%' . $title . '%')
->where('published', 1)
->with(['medias AS jpeg' => function($q) {
$q->where('format', 'jpeg');
}])->with(['medias AS gif' => function($q) {
$q->where('format', 'gif');
}])->first();
我知道这行不通,但这是为了给你一个情况。
有可能还是我必须手动这样做?
提前谢谢你。
这
是不可能的,因为with
不接受表,而是接受关系名称,并且它只存储给定关系的结果一次。
因此,只需定义不同的关系:
public function gifs()
{
return $this->hasMany('Media')->where('format', 'gif');
}
public function jpegs()
{
return $this->hasMany('Media')->where('format', 'jpeg');
}
显然hasMany
或任何关系类型。