首页 文章

Laravel Eloquent ORM还有许多其他枢轴关系存在的地方

提问于
浏览
0

我想查询hasMany关系的所有模型,这些关系也与指定的其他模型具有透视关系 .

例:

Customer:
  belongsToMany -> Entry
EntryGroup:
  hasMany -> Entry
Entry:
  belongsToMany -> Customer
  belongsTo -> EntryGroup

Customer和Entry之间的belongsToMany关系存储在数据透视表中 .

我现在想要收集属于EntryGroup上指定客户的所有条目的关系 . 没有这个过滤限制,我会有一个像这样的功能

class EntryGroup extends Model
{
    ...

    public function entries()
    {
        return $this->hasMany(Entry::class);
    }
}

提前感谢您提出的任何建议 .

3 回答

  • 0

    试试这个$ customers-> entries() - > with('entryGroup') - > get();

  • 0

    试试这个:

    <?PHP
    
       $customerId = 5;
    
        Entry::whereHas('customer', function ($query) use ($customerId) {
            $query->where('id', $customerId);
        })->has("EntryGroup")->get();
    

    这返回所有条目都有一个entrygroup并且属于customer id 5

  • 0

    试试这个:

    $entryGroup->entries()->whereHas('customer', function ($query) use ($customerId) {
        $query->where('customers.id', $customerId);
    })->get();
    

相关问题