简体   繁体   中英

Eloquent has() in Many-To-Many

I'm having a simple blog system, with a posts , tags and posts_tags table. The posts and tags table both have an id and a content field, whereas the posts_tags table has the fields post_id and tag_id . My eloquent models are:

class Post extends \Illuminate\Database\Eloquent\Model
{
    public function tags()
    {
        return $this->belongsToMany('Tag', 'posts_tags', 'post_id', 'tag_id');
    }
}

and

class Tag extends \Illuminate\Database\Eloquent\Model
{
    public function posts()
    {
        return $this->belongsToMany('Post', 'posts_tags', 'tag_id', 'post_id');
    }
}

Now, as far as I understood, if I call Post::has('tags')->get() I should get the posts which have at least one tag (which all do). But all I get is an empty array (which I get when calling Tag::has('posts')->get() , too). What am I doing wrong?

Ok, found the problem in this question: Laravel Eloquent::Find() returning NULL with an existing ID

Problem was, I was using soft deletes

class Post extends \Illuminate\Database\Eloquent\Model
{
    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

    public function tags()
    {
        return $this->belongsToMany('Tag', 'posts_tags', 'post_id', 'tag_id');
    }
}

But my deleted_at column wasn't nullable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM