A
A
axblue2016-11-11 20:58:15
Laravel
axblue, 2016-11-11 20:58:15

How to remove all posts from categories?

Hello. Conditionally there are posts, there are categories. Implemented a one-to-many relationship. How can I now get a category through a post?

class Tag extends Model
{
    public function recipes() {
        return $this->hasMany('App\Recipe');
    }
}

class Recipe extends Model
{
    public function tags()
    {
        return $this->belongsTo('App\Tag');
    }

$posts = Recipe::with('tags')->get();
@foreach($recipes as $recipe)
$recipe->tags->name  //так не могу получить имя категории данного поста, что я делаю не так?
  @endforeach

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2016-11-11
@leshikgo

The structure used to maintain tags for materials is not entirely clear.
Implement the following architecture:
6bea3a74a58e446dbba5b26c00e3a7b9.png

class Recipe extends Model
{
  public function tag_links()
  {
    return $this->hasMany('Recipe_Tag', 'recipe_id');
  }
}

class Recipe_Tag extends Model
{
  public function tag()
  {
    return $this->hasOne('Tag', 'tag_id');
  }
}

class Tag extends Model
{
}

Usage:
$receipes = Recipe::with('tag_links')->get();
foreach ($receipes as $receipe)
{
  echo '<h1>'.$receipe->title.'</h1>';
  echo 'Категории: ';
  foreach ($receipe->tag_links as $tag_link)
  {
    echo $tag_link->tag->name;
  }
}

There is no need to explain the advantage of this approach.
PS An example of displaying information through the controller - provided for clarity.
Good luck! ;-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question