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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?