我有这样的声明,它工作正常,但没有我想要的那么好:
$recipes = DB::table('recipes')
->join('category_recipe', 'recipes.id', '=', 'category_recipe.recipe_id')
->join('category', 'category.id', '=', 'category_recipe.category_id')
->join('users', 'users.id', '=', 'recipes.user_id')
->where('category.id', '=', $cat_id)->get(array('recipes.*','users.*'));
如何将其翻译为 Eloquent?
为什么?
我想将一个 View 用于多种方法。
这个 View 或 foreach 看起来像这样:
@foreach($recipes as $recipe)
{{link_to_route('recipe_details',$recipe->title,array('id'=>$recipe->id))}} - By {{ $recipe->user->firstname }} - Category: @foreach($recipe->category as $cat) {{ $cat->title }} @endforeach </br>
@endforeach
如您所见,我正在使用“用户”关系。显然这个 foreach 不适用于顶部的查询,因为没有“用户”模型。
那么如何将查询转换为 Eloquent?
我试过了
$recipes = Recipe::with('category')->where('category_id',$cat_id)->get();
但这行不通。有什么提示吗?
这是我的模型:
食谱.php
public function user() {
return $this->belongsTo('User','user_id');
}
public function category() {
return $this->belongsToMany('Category','category_recipe');
}
类别.php
public function recipes() {
return $this->belongsToMany('Recipe');
}
用户.php
public function recipes() {
return $this->hasMany('Recipe','user_id');
}
谢谢!
最佳答案
你可以试试这个:
$recipes = Recipe::with(array('user', 'categories' => function($q) use ($cat_id) {
$q->where('id', $cat_id);
}))->get();
更改如下:
public function category() {
return $this->belongsToMany('Category','category_recipe');
}
至(category
应为 Recipe.php
中的 categories
):
public function categories() {
return $this->belongsToMany('Category','category_recipe');
}
顺便说一句,您也可以像这样使用 join
(如果您在任何情况下需要,请使用 Eloquent
模型):
Recipe::join('category_recipe', 'recipes.id', '=', 'category_recipe.recipe_id')
->join('category', 'category.id', '=', 'category_recipe.category_id')
->join('users', 'users.id', '=', 'recipes.user_id')
->where('category.id', '=', $cat_id)->get();
更新:您也可以尝试以下操作:
$recipes = Recipe::whereHas('categories', function($q) use ($cat_id) {
$q->where('id', $cat_id);
})->with('user')->get();
关于php - laravel - 查询生成器与 Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22813989/