Eloquent在多对多中有()

Eloquent在多对多中有()

问题描述:

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.