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.

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

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了