laravel多重关系查询

laravel多重关系查询,laravel,eloquent,laravel-query-builder,Laravel,Eloquent,Laravel Query Builder,我的项目中有3个模型,我想得到一个查询或收集结果,如我所说: JewelsItem模型: protected $table = 'jewel_items'; public function jewel(){ return $this->belongsTo('App\Models\Jewel'); } public function sellInvoice(){ return $this->belongsTo(SellInvoice::class,'sell_invoice_

我的项目中有3个模型,我想得到一个查询或收集结果,如我所说:

  • 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.1发票型号:

        protected $table = "sell_invoices";
    
    public function jewelsItems(){
        return $this->hasMany(JewelsItem::class,'buy_invoice_id');
    }
    
    查询:我想获取所有没有sellInvoice且珠宝名称为“某物”的珠宝网站

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

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

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

    但我无法将所有与之相关的jewelItem都添加到第一个关系中。

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

    它的内容是:获取jewel在名称字段中有$name的jewel项目
    并且没有销售发票
    然后将相关宝石添加到宝石项目

    当您想要检索宝石的名称时,您可以像这样访问它的属性

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