Laravel 4:如果关系存在通过查询关系选择行 [英] Laravel 4: Select row if a relation exists by querying relation
问题描述
我正在尝试查询产品表,并希望它在关系存在时返回一个集合.
I am trying to query a products table, and want it to return a collection if a relation exists.
迭代1查询products表中的所有行,如果$name
匹配,则延迟加载metals表.这是错误的.
Iteration 1 below queries all rows in the products table, and lazy loads the metals table if $name
matches. This is wrong.
我的路线:
Route::group(array('prefix' => '{api}/v1'), function()
{
Route::controller('products', 'ApiV1ProductController');
});
我的控制器:
public function getFilter($metal = null) {
$products = $this->product;
if ($metal) {
$products->with('metal', function($query, $metal) {
$query->where('name', $metal);
});
}
return Response::api($products->get());
}
如果metal.name = $metal
,我希望仅 $products
显示.例如类似:
I want only $products
to display if metal.name = $metal
. e.g. something like:
$this->products->where('metal.name', $metal)->get;
使用 Glad To Help 部分答案的解决方案:
这提供了一种替代方法 2,无需连接.
This provides an alternative approach 2, without the need for joins.
推荐答案
不幸的是,您还不能在 Eloquent 中通过一次滑动来完成此操作.
Unfortunately you cannot do this with one swipe in Eloquent yet.
但是,有一种使用逆关系的方法,如下所示:
BUT, there is a way by using the inverse relation, like this:
public function getFilter($metal = null)
{
// filter the metals first
$metals = Metal::with('products')->where('name', '=' , $metal)->get();
$products = array();
foreach($metals as $metal)
{
// collect the products from the filtered metals
$products = array_merge($products, $metal->products->toArray() );
}
return $products;
}
如果这对您来说不是一个优雅的解决方案,您将不得不使用 Fluent 来构建查询并手动加入 products x metal 表,或者通过覆盖 newQuery() 方法预先加入它们.
If this is not elegant solution for you, you will either have to use Fluent to construct the query and join the products x metals table manually or pre-join them by overriding the newQuery() method.
1) 替代方法一.
public function getFilter($metal = null) {
return DB::table('products')->join('metal', 'products.id', '=' , 'metal.product_id')
->where('metal.name', $name)
->select(array('products.*'));
}
2) 替代方法二
class Product extends Eloquent{
public function newQuery($excludeDeleted = true){
return parent::newQuery()->join('metal','id','=','metal.product_id');
}
}
这篇关于Laravel 4:如果关系存在通过查询关系选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!