douwei1921 2018-06-28 11:42
浏览 52
已采纳

Laravel - 语法错误或访问冲突:1066不唯一的表/别名

I have a model for users

class User
{
    protected $primaryKey = 'user_id';

    public function blocks()
    {
        return $this->belongsToMany(Block::class, 'block_user', 'blocker_id', 'blocked_id')->withTimestamps();
    }
}

And a model for blocks

class Block extends Model
{
    protected $table = "block_user";
}

So I have two tables: one for user information and the other for when one blocks another(Pivot Table) so user_id in users table is both local and foreign.

The problem is that when I want to get if user has blocked another user it returns an error saying: Syntax error or access violation: 1066 Not unique table/alias: 'block_user'

$user = User::where('user_id', 1)->first();
dd($user->blocks->first_name);

How can I fix it? Thanks

  • 写回答

1条回答 默认 最新

  • doujiku1028 2018-06-28 12:08
    关注

    You are relating the User model to the User model, not to the Block model. A model for a pivot table is not necessary and usually would never be used.

    public function blocks()
    {
        return $this->belongsToMany(User::class, 'block_user', 'blocker_id', 'blocked_id')->withTimestamps();
    }
    

    So instead of relating to Block::class in your belongsToMany, relate to User::class.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部