【发布时间】:2014-05-13 21:15:52
【问题描述】:
我有这个声明,它工作正常,但没有我想要的那么好:
$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?
为什么?
我想为多种方法使用一个视图。
这个视图或 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 不适用于顶部的 Query,因为没有“用户”模型。
那么如何将 Query 翻译成 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');
}
Category.php
public function recipes() {
return $this->belongsToMany('Recipe');
}
用户.php
public function recipes() {
return $this->hasMany('Recipe','user_id');
}
谢谢!
【问题讨论】:
标签: php mysql laravel eloquent