gpt4 book ai didi

mysql - Laravel 热切加载关系与添加的子句?

转载 作者:行者123 更新时间:2023-11-29 15:29:30 25 4
gpt4 key购买 nike

我有两个相关的表:UsersImages

class User extends Model
{
public function images()
{
return $this->hasMany('App\Images');
}
}

class Image extends Model{

public function user()
{
return $this->belongsTo('App\User');
}
}

我正在尝试在名为 thumbnailsUser 模型上添加第二种方法,该方法允许我立即加载一组特定的用户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 第一个 Post 模型。我的thumbnails方法有问题吗?

最佳答案

您的 limit 调用不会将 1 个用户的图像限制为 3 个,而是将所有帖子用户的图像的整个查询限制为 3 个。它只会为所有帖子找到 3 个图像。用户。

您现在可以删除该限制:

public function thumbnails()
{
return $this->images()->where('processed', true);
}

关于mysql - Laravel 热切加载关系与添加的子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58830115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com