简体   繁体   English

Laravel雄辩关系按关系列过滤

[英]Laravel Eloquent Relationship Filter by Column of Relationship

I have 3 Tables 我有3张桌子

Product:[Table] 产物:[表]

Person:[Table] 人:[表]

Payment:[Table] 付款:[表]

Many To Many Relationship Between Product and Person 产品与人之间的多对多关系

One To Many Relationship Between Product and Payment (One Product Has Many Payments) 产品与付款之间的一对多关系(一种产品有很多付款)

One To Many Relationship Between Person and Payment (One Person Has Many Payments) 人与付款之间的一对多关系(一人有多付款)

Payment:[Table]
    id
    person_id
    product_id
    amount

The thing is that i am trying to get All persons with products and Product payments filtered by person_id . 问题是我试图通过person_id过滤所有人的产品和产品付款。

Reason is that i dont want to have any other persons record in payments. 原因是我不希望任何其他人记录付款。

This is actually the query i am running yeah i know its wrong cuz i cant filter it by person_id . 这实际上是我正在运行的查询是的我知道它错了因为我person_id过滤它。

$query = $person::with('product', 'payment')->where('is_active', 1);

I want to achieve something like this.. 我想达到这样的目的..

 $query = $person::with(array('product', 'payment' => function ($query) {
    $query->where('person_id', '=', 'person.id');
}))->where('is_active', 1);

If you setup your relations like: 如果你设置你的关系,如:

class Person extends Model
{
    public function payments()
    {
        return $this->hasMany(Payment::class);
    }
}

class Payment extends Model
{
    public function product()
    {
        return $this->belongsTo(Product::class);
    }
}

Then you should be able to do: 然后你应该能够做到:

$person = Person::with('payments.product')->where('id',$personId)->where('is_active',1)->first();

Which will return a Person with all the relations loaded and you can access those like: 这将返回一个加载了所有关系的Person ,你可以访问以下内容:

@foreach($person->payments as $payment)
    {{$person->name}} bought {{$payment->product->name}} for {{$payment->amount}}
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM