douwei1921 2018-06-28 19:42
浏览 47
已采纳

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 20: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.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器