Laravel可成像类型和过滤

时间:2017-05-24 16:08:12

标签: php laravel

我有一个可成像的产品

Product.php

public function imageable()
{
    return $this->morphTo('imageable');
}

这种变形的车辆

public function products()
{
  return $this->morphMany('App\Product', 'imageable');
}

例如,如果我想获得车型,我可以用$product->imageable->model调用它。

但是我如何在查询中执行此操作,特别是这样:

$products = \App\Product::where('imageable_type', 'App\Vehicle')

$products->where($products->imageable->make, 'Ford')

上面的这一行是伪代码,但它是我试图实现的原则,这甚至可能吗?我本质上希望能够通过Make过滤车辆,但该细节存在于产品的可成像模型中。

将我的查询更改为:

后编辑
if($make = request('make')){
                $products->where('imageable_type', 'App\Vehicle')
                ->whereHas('imageable', function($query) {
                    $query->where('make', request('make'));
                });
            }

如下所示,我收到以下错误:

`SQLSTATE[42S22]: Column not found: 1054 Unknown column 'make' in 
'where clause' (SQL: select * from `products` where 
(`products`.`user_id` != 3 and `products`.`status` = 0) and `category` 
= Cars and `imageable_type` = App\Vehicle and exists (select * from 
`products` as `laravel_reserved_0` where `laravel_reserved_0`.`id` = 
`laravel_reserved_0`.`imageable_id` and `make` = Tesla))`

将make作为请求参数传递时

由于

1 个答案:

答案 0 :(得分:2)

试试这个:

\App\Product::where('imageable_type', App\Vehicle::class)
    ->whereHas('imageable', function($query) {
        $query->where('make', 'Ford');
    })->get();

更新

在产品模型中

name关系添加morphTo

public function imageable()
{
    return $this->morphTo('imageable');
}

更新

我认为它不适用于您,因为当关系为morpTo时有bug

也许你应该以另一种方式做到这取决于你的需要:

Ex:1

// in this way you will get all Vehicle made by ford and eager load the products, then you make some process to get all products.
$vehicles = \App\Vehicle::with('products')->where('make', 'Ford')->get();

foreach($vehicles as $vehicle) {
    // I put the condition because maybe there are some vehicles without products
    $productName = $vehicle->products->count() ? $vehicle->products->first()->name : '';    
}

Ex:2

\App\Product::leftJoin('vehicles', function(JoinClause $join)
    {
        $join->on('products.imageable_id', '=', 'vehicles.id')
            ->on('products.imageable_type', '=', \DB::raw("'App\\Vehicle'"));
    })
    ->where('vehicles.make', 'Ford')
    ->where('products.imageable_type', App\Vehicle::class)
    ->get()