Laravel在模型中定义多个foregin键并出现错误

时间:2018-07-01 09:22:28

标签: php laravel laravel-5.6

此迁移为:

Schema::create('user_tickets', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->string('subject');
    $table->integer('ticket_number')->unique();
    $table->tinyInteger('priority')->default(2);
    $table->tinyInteger('section');
    $table->boolean('solved')->default(false);
    $table->timestamps();
});

Schema::create('user_tickets_answers', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->integer('ticket_id')->unsigned();
    $table->foreign('ticket_id')->references('id')->on('user_tickets')->onDelete('cascade');
    $table->text('reply',200);
    $table->timestamps();
});

laravel为我创建此外键

user_tickets_answers_user_id_foreign
user_tickets_answers_ticket_id_foreign

user_tickets_answers表上,现在当我尝试获取具有user_tickets关系的user_tickets_answers数据时,例如:

$tickets = UserTickets::with('reply')->get();

我收到此错误:

Base table or view not found: 1146 Table 'diabet.user_ticket_answers' doesn't exist (SQL: select * from `user_ticket_answers` where `user_ticket_answers`.`ticket_id` in (1))

如何在自模型中定义此外键?

UserTickets:

class UserTickets extends Model
{
    protected $guarded = ['id'];

    public function reply()
    {
        return $this->hasMany(UserTicketAnswers::class, 'ticket_id');
    }
}

UserTicketAnswers:

class UserTicketAnswers extends Model
{
    protected $guarded = ['id'];

    public function ticket()
    {
        return $this->belongsTo(UserTickets::class);
    }
}

2 个答案:

答案 0 :(得分:2)

尝试更改该语句(如果可行),因为以前发生此错误时,它对我有用。可以肯定的是,再次检查Documentation,以传递自定义键,例如

  

('App \ Phone','foreign_key','local_key');


在UserTickets模型更改中

return $this->hasMany(UserTicketAnswers::class, 'ticket_id'); 

return $this->hasMany('App\UserTicketAnswers','ticket_id','id');


在UserTicketAnswers

return $this->belongsTo(UserTickets::class);

return $this->belongsTo('App\UserTickets','ticket_id','ticket_id');


与您的User模型相同的逻辑。

public function userTickets(){
    return $this->hasMany('App\UserTickets','user_id','id');
}

public function userTicketAnswers(){
    return $this->hasMany('App\UserTicketAnswers','user_id','id');
}


将它们分别添加到UserTicketsUserTicketAnswers模型中

public function user{
    return $this->belongsTo('App\Users','user_id','user_id');
}

答案 1 :(得分:1)

您的表名称在迁移中有所不同,在查询数据库中的 user_tickets_answers 表时,它是 user_tickets_answers