Laravel 多关系查询

发布时间:2021-02-25 11:29

我的项目中有 3 个模型,我想像我说的那样获得查询或收集结果:

  1. JewelsItem 模型:

    protected $table = 'jewel_items';
    
    public function jewel(){
     return $this->belongsTo('App\Models\Jewel');
    }
    
     public function sellInvoice(){
     return $this->belongsTo(SellInvoice::class,'sell_invoice_id');
    }
    

2.宝石模型:

public function jewelsItems(){
    return $this->hasMany('App\Models\JewelsItem');
}

3.sellInvoice模型:

    protected $table = "sell_invoices";

public function jewelsItems(){
    return $this->hasMany(JewelsItem::class,'buy_invoice_id');
}

查询:我想获取所有没有销售发票且珠宝名称为“某物”之类的珠宝网站。

注意:珠宝模型有一个名称属性。我想将珠宝的名称添加到所有集合的结果项中。

我知道如何获得所有名称为“某物”的珠宝:

Jewel::where('name','like','something'.'%')->get();

但我无法获得所有与它相关的珠宝项目,并在其中第一个添加珠宝名称。

回答1

要在另一个关系中查找条件,您可以使用 whereHas()whereDoesntHave()

$name = 'something';
$items = JewelsItem::whereHas('jewel', function($query) use ($name) {
    $query->where('name', 'LIKE', "%{$name}%");
})
->whereDoesntHave('sellInvoice')
->with('jewel')
->get();

它写着:获取珠宝在名称字段中具有 $name 的珠宝项目
并且没有销售发票
然后将相关的珠宝添加到珠宝项目中。

当你想检索珠宝的名字时,你可以像这样访问它的属性。

foreach($items as $item) {
    echo $item->jewel->name;
}