dongxia4880 2015-06-29 21:40
浏览 43
已采纳

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?

  • 写回答

1条回答 默认 最新

  • duanshang7007 2015-07-21 18:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大