【问题标题】:Filter models with pivot table extra field value in laravel在 laravel 中过滤具有数据透视表额外字段值的模型
【发布时间】:2018-12-31 17:20:46
【问题描述】:

我有三张桌子

tours (id , body) -> assume a record is (id: 1, body: somethings)

metas (id , key)-> assume a record is (id: 1, key: tour_price)

metables (meta_id , metable_id, metable_type, value) -> assume a record is: (meta_id: 1, metable_id: 1 , metable_type: App\Tour , value : 250000)

我想要这样的元值过滤结果:

where tour_price is 250000 ?

我的 Tour 模型也有这样的功能:

public function metas()
{
    return $this->morphToMany('App\Meta', 'metable')->withPivot('value');
}

我试过这个:

$tours = Tour::whereHas('metas', function($q){
    $q->where('key','tour_price');
})->get()

它只是在数据透视表中返回带有 tour_price 键的游览。我想要这样的东西:

$tours = Tour::whereHas('metas', function($q){
    $q->where('key.tour_price','250000');
})->get()

但它不起作用。

我的表格结构:

元数据: View Image

元表:

View Image

【问题讨论】:

  • 为什么要创建多态关系?我认为应该是 toursmetas 之间的多对多关系
  • 我想在我的应用程序中为其他模型使用元数据。出于这个原因,我添加了多态关系。这是不对的 ?可以在 laravel 中使用与简单的多对多关系相同的多态多对多关系吗?
  • 你试过$q->where('key','tour_price')->wherePivot('value', 250000); 吗?
  • 是的,它不起作用

标签: php laravel eloquent


【解决方案1】:

找到了! 解决办法是:

$q->where('key','tour_price')->where('value', 250000);

如果你想使用多个条件,你可以试试:

Tour::whereHas('locations', function($q){
        $q->where('slug','=','istanbul');
    })
        ->whereHas('metas', function($q){
            $q->where('key','tour_start_date')
                ->where('value','>=', '2018-07-23 00:00:00');
        })
        ->whereHas('metas', function($q){
            $q->where('key','tour_end_date')
                ->where('value','2018-08-05 00:00:00');
        })->get();

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2015-05-29
    • 2018-01-18
    • 2014-12-21
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多