Laravel:如何在多态中使用wherePivot多对多

问题描述 投票:0回答:1

我想在我的数据透视表中查询isrecurring = 1的位置,但没有找到现有的解决方案。任何人都有任何经验以及如何在多对多多态数据透视表中获取“isrecurring”= 1的所有记录?

Example.
$enroll->products->where('isrecurring', 1);

but in enrollable pivot table
-> get all records that 'isrecurring' = 1

我的模特(没有wherePivot)

Enroll.php
------
public function products(){
return $this->morphedByMany('App\Models\Product', 'enrollable')->withPivot('isrecurring');
}

Product.php
----
public function enrolls(){
return $this->morphToMany('App\Models\Enroll', 'enrollable')->withPivot('isrecurring');
}

我的数据库

enrolls
-----
id


products
----
id

enrollables
----
enroll_id
enrollable_id
enrollable_type
isrecurring    (boolean)

我希望使用wherePivot,但似乎无法工作,无法查询。

Product.php
----
public function enrolls(){
return $this->morphToMany('App\Models\Enroll', 'enrollable')->withPivot('isrecurring')->wherePivot('isrecurring', '=', 1);
}
laravel eloquent polymorphism relationship
1个回答
0
投票

我有同样的问题,可以使用以下方法解决它:

//Model: User.php

public function certificates()
{
    return $this->morphedByMany('App\Certificate', 'appliable')
        ->withTimestamps();
}

//Controller: EnrollmentController.php

$usersWithCertificates = User::whereHas('certificates', function($query){
    $query->where('status', '0');
})->with('certificates')->latest()->paginate(10);

使用function($query){ }添加数据透视表的自定义SQL

你可以在这里阅读Laravel文档中的更多内容:查询关系存在部分中的https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence

© www.soinside.com 2019 - 2024. All rights reserved.