dimanche 12 novembre 2017

Eloquent query: Filtering results based on relationship with other model

So I have two tables: posts and categories. It is a many-to-many relationship: A post has many categories and a category belongs to many posts. Here are the models that describe their relationships:

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name', 'slug'];

    public function posts()
    {
        return $this->belongsToMany('App\Post');
    }
}

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

I want to get all posts that have a particular category: tips

Here is what I tried:

$tips = Category::where('name', 'Tips')->posts()->with('categories')->take(4)->get();

I don't know the level of ignorance in this query, but I honestly expected it to work. It didn't.

I'll appreciate any help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2hncnp3
via IFTTT

Aucun commentaire:

Enregistrer un commentaire