У меня есть это заявление, которое работает нормально, но не так хорошо, как я хочу:
$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 
Как вы можете видеть, я использую отношения «пользователь». Очевидно, что этот foreach не работает с Query вверху, потому что нет «пользовательской» модели.
  Итак, как я могу перевести Query in Eloquent? 
  Я пытался 
 $recipes = Recipe::with('category')->where('category_id',$cat_id)->get(); 
Но это не работает. Любые подсказки, пожалуйста?
  Вот мои модели: 
  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(); 
Изменения, следующие:
 public function category() { return $this->belongsToMany('Category','category_recipe'); } 
  К ( category должна быть categories в Recipe.php ): 
 public function categories() { return $this->belongsToMany('Category','category_recipe'); } 
  Btw, вы также можете использовать 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();