我有两个相关的表:Users和Images
class User extends Model
{
public function images()
{
return $this->hasMany('App\Images');
}
}
class Image extends Model{
public function user()
{
return $this->belongsTo('App\User');
}
}我正尝试在名为thumbnails的User模型上添加第二个方法,该方法允许我立即加载一组特定的用户Images,而不必首先加载所有用户图像。逻辑如下:
public function thumbnails () {
return $this->hasMany('App\Images')
->selectRaw('src, user_id')
->where('processed', true)
->limit(3);
}下面是我对此关系的调用方式:
$posts = Post::with(['user','user.thumbnails'])->get();使用debugbar,我检查了这个查询:
"sql": "select src, user_id from \"images\" where \"processed\" = 1 and \"images\".\"user_id\" in (12, 14, 15) limit 3", 这只返回user.thumbnails first Post模型。我的thumbnails方法有问题吗?
发布于 2019-11-13 12:04:48
您可以在内部查询中调用scope。
class User extends Model{
public function scopeThumbnails($query)
{
return $query->where('processed', true)
->limit(3);
}
}在你的控制器中
$posts = Post::with(['user' => function($query) {
$query->thumbnails();
}])->get();https://stackoverflow.com/questions/58830115
复制相似问题