【问题标题】:How can i put condition in relation in laravel?我如何在laravel中放置条件?
【发布时间】:2020-08-18 23:42:09
【问题描述】:

我有 File 模型来存储我的图像,并且我有 shop 模型,商店可以有许多图像,并且在商店模型中我编写了以下代码:

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

我想用它的图像检索商店模型,现在我的问题是如何将 where 条件放在相关的位置。我的检索商店模型的代码是:

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


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

【问题讨论】:

    标签: laravel model relation data-retrieval wherehas


    【解决方案1】:

    型号

    public function all() { 
         return $this->hasManyThrough('ShopType', 'User', 'Files');
    } 
    

    然后

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

    【讨论】:

    • 如何在此代码中添加它:$shop = Shop::where('id', $id)->with('ShopType', 'User', 'Files')->get();
    • 您可以在模型public function all() { return $this->hasManyThrough('ShopType', 'User', 'Files'); }$shop = shop::with('all')->where('id',$id)->get(); 中使用此语法
    【解决方案2】:

    你可以使用 constraining-eager-loads:

    $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

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2017-11-11
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2019-05-27
      • 2021-11-18
      相关资源
      最近更新 更多