Php laravel-查询生成器vs.雄辩

Php laravel-查询生成器vs.雄辩,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,我有这样一个声明,它运行良好,但没有我想要的那么好: $recipes = DB::table('recipes') ->join('category_recipe', 'recipes.id', '=', 'category_recipe.recipe_id') ->join('category', 'category.id', '=', 'category_recipe.category_id')

我有这样一个声明,它运行良好,但没有我想要的那么好:

        $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.*'));  
我怎样才能把这个翻译成雄辩的

为什么?
我想对多个方法使用一个视图。
此视图或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  
但这不起作用。有什么提示吗

以下是我的型号:
Recipe.php

    public function user() {
        return $this->belongsTo('User','user_id');
}
public function category() {
        return $this->belongsToMany('Category','category_recipe');
}  
Category.php

    public function recipes() {
    return $this->belongsToMany('Recipe');
}  
User.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();
$recipes = Recipe::whereHas('categories', function($q) use ($cat_id) {
    $q->where('id', $cat_id);
})->with('user')->get();
更改如下:

public function category() {
    return $this->belongsToMany('Category','category_recipe');
}
To(
Recipe.php
中的
categories
应该是
categories
):

顺便说一句,您也可以像这样使用
join
(如果您在任何情况下需要,请使用
elount
模型):

更新:您也可以尝试以下操作:

$recipes = Recipe::with(array('user', 'categories' => function($q) use ($cat_id) {
    $q->where('id', $cat_id);
}))->get();
$recipes = Recipe::whereHas('categories', function($q) use ($cat_id) {
    $q->where('id', $cat_id);
})->with('user')->get();

谢谢我会试试看。我尝试了join方法,但这仍然不能使§recipes->user->firstname起作用,我需要它来运行其他方法。但好吧,我试试你的第一个建议!:)<代码>§recipes->user->firstname不起作用,因为
get()
返回一个集合,因此您需要使用
first()
来获取第一个项目,如果有多个项目,则可以使用循环。试试看,
§recipes->first()->user->firstname
作为第一个。您的版本似乎可以运行,但我无法正确地执行“where”。它显示了类别ID=6的所有行,而不是(在本例中)只有两行。这是我的代码:如果您只想获取包含类别的行,那么使用
whereHas
应该是另一种方法。您还可以添加
->where('category.id',$cat\u id)->get()
$recipes = Recipe::whereHas('categories', function($q) use ($cat_id) {
    $q->where('id', $cat_id);
})->with('user')->get();