首页 > 解决方案 > 我如何在laravel中放置条件?

问题描述

我有存储我的图像的文件模型,我有商店模型,商店可以有很多图像,在商店模型中我写了这个代码:

public function Files()
    {
        return $this->hasMany('system\models\file', 'attachment_id');
    }

我想用它的图像检索商店模型,现在我的问题是我怎样才能把条件放在哪里。我检索商店模型的代码是:

$shop = Shop::where('id', $id)->with('ShopType', 'User', 'Files')->get();


注意:我需要为调用 attachment_id 的 Files 方法中设置的主题之一的关系设置 2 个条件,而我的第二个条件是 attachment_type 请帮助我。谢谢

标签: laravelmodelrelationdata-retrievalwherehas

解决方案


您可以使用约束急切负载:

$shop = Shop::with(['ShopType','User', 'Files'=>function ($query)use($id)
{
query->where('id', $id);
}
])->get();

更多细节在:

https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads


推荐阅读