我有一个可成像的产品
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作为请求参数传递时
由于
答案 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()