php - 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')
            ->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/

相关文章:

php - 无法在 PHP 中打印变量的值

php - 检查并确认

php mysql查询仅获取列中的第一个值

php - 如何在mysql中存储媒体文件路径

php - Laravel 测试 dontSee 否定英文文本

php - Mysql 不接受表单输入 Laravel 5.2

laravel - 如何从 Behat 测试内部运行 shell 命令?

php - 为什么在 ajax 请求中使用 JSON 或者为什么不使用

php - Yii2 登录后重定向到上一页

mysql - 第 1 行附近的间隔 : Caused by: org. hibernate.hql.internal.ast.QuerySyntaxException