SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/关系别名

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship(SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/关系别名)
本文介绍了SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/关系别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我从 Laravel 框架收到以下错误;但我找不到这个框架产生这个错误的原因:

So, I'm receiving the following error from Laravel framework; but I couldn't find why this framework is producing this error:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'participants' (SQL: select `participants`.*, `participants`.`message_id` as `pivot_message_id`, `participants`.`user_id` as `pivot_user_id`, `participants`.`created_at` as `pivot_created_at`, `participants`.`updated_at` as `pivot_updated_at` from `participants` inner join `participants` on `participants`.`id` = `participants`.`user_id` where `participants`.`deleted_at` is null and `participants`.`message_id` in (2))

我的消息/参与者关系如下所示:

My message/participants relationship looks like this:

public function participants()
{
    return $this->belongsToMany('NamespaceModulesEmailModelsParticipant', 'participants', 'message_id', 'user_id')->withTimestamps();
}

我试着这样称呼它:

public function getAllMessages()
{
   return Message::with('user')->with('participants')->get();
}

为什么我会收到这个错误?这是怎么回事?

Why am I getting this error? What's going on?

包括完整模型

留言

class Message extends Eloquent
{
    use PublishedTrait;
    use SoftDeletingTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'messages';

    /**
     * The attributes that can be set with Mass Assignment.
     *
     * @var array
     */
    protected $fillable = ['subject', 'user_id', 'body', 'status'];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];

    /**
     * Validation rules.
     *
     * @var array
     */
    protected $rules = [
        'subject' => 'required|max:255',
        'body' => 'required',
    ];

    /**
     * User relationship
     *
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function user()
    {
        return $this->belongsTo(Config::get('email.user_model'));
    }

    public function assets()
    {
        return $this->belongsToMany('NamespaceModulesAssetsModelsAsset', 'message_assets');
    }

    /**
     * Participants relationship
     *
     * @return IlluminateDatabaseEloquentRelationsHasMany
     */
    public function participants()
    {
        return $this->belongsToMany('NamespaceModulesEmailModelsParticipant', 'participants', 'message_id', 'user_id')->withTimestamps();
    }

    /**
     * Recipients of this message
     *
     * @return IlluminateDatabaseEloquentRelationsHasMany
     */
    public function recipients()
    {
        return $this->participants()->where('user_id', '!=', $this->user_id);
    }

    /**
     * Returns the latest message from a thread
     *
     * @return NamespaceModulesEmailModelsMessage
     */
    public function getLatestMessageAttribute()
    {
        return $this->messages()->latest()->first();
    }

    /**
     * Returns threads that the user is associated with
     * @param $query
     * @param $userId
     * @return mixed
     */
    public function scopeForUser($query, $userId)
    {
        return $query->join('participants', 'messages.id', '=', 'participants.message_id')
            ->where('participants.user_id', $userId)
            ->where('participants.deleted_at', null)
            ->select('messages.*');
    }

    /**
     * Returns threads that the user is associated with
     * @param $query
     * @param $userId
     * @return mixed
     */
    public function scopeForUserWithDeleted($query, $userId)
    {
        return $query->join('participants', 'messages.id', '=', 'participants.message_id')
            ->where('participants.user_id', $userId)
            ->select('messages.*');
    }

    /**
     * Returns messages that the user has sent
     * @param $query
     * @param $userId
     * @return mixed
     */
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Returns threads with new messages that the user is associated with
     * @param $query
     * @param $userId
     * @return mixed
     */
    public function scopeForUserWithNewMessages($query, $userId)
    {
        return $query->join('participants', 'messages.id', '=', 'participants.message_id')
            ->where('participants.user_id', $userId)
            ->whereNull('participants.deleted_at')
            ->where(function ($query) {
                $query->where('messages.updated_at', '>', $this->getConnection()->raw($this->getConnection()->getTablePrefix() . 'participants.last_read'))
                    ->orWhereNull('participants.last_read');
            })
            ->select('messages.*');
    }

}

参与者

class Participant extends Eloquent
{
    use SoftDeletingTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'participants';

    /**
     * The attributes that can be set with Mass Assignment.
     *
     * @var array
     */
    protected $fillable = ['message_id', 'user_id', 'last_read'];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['created_at', 'updated_at', 'deleted_at', 'last_read'];

    /**
     * Thread relationship
     *
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function message()
    {
        return $this->hasMany('NamespaceModulesEmailModelsMessage');
    }

    /**
     * User relationship
     *
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function user()
    {
        return $this->belongsTo(Config::get('email.user_model'));
    }
}

推荐答案

通过 Laracat 官方 Slack 回答:

Answered via the Larachat official Slack:

该关系缺少一个数据透视表以使其正常工作.participants 方法中的第二个参数是要使用的数据透视表:

The relationship is missing a pivot table for this to work. The second argument in the participants method is the pivot table to use:

public function participants()
{
    return $this->belongsToMany('NamespaceModulesEmailModelsParticipant', 'PIVOT', 'message_id', 'user_id')->withTimestamps();
}

因此,您不能使用参与者作为数据透视表,因为它是关系中的表之一,您需要一个message_participant 数据透视表.

Therefore, you can't use participants as the pivot because it is one of the tables in the relationship, you need a message_participant pivot table.

这篇关于SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/关系别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)