Laravel在模型中定义多个外键并获得错误

for this migration as:

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();
});

and

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 create this foreign keys for me

user_tickets_answers_user_id_foreign
user_tickets_answers_ticket_id_foreign

on user_tickets_answers table, now when i try to get user_tickets data with user_tickets_answers relation such as:

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

i get this error:

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))

how can i define this foreign keys on self models?

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);
    }
}

Your table name is different in migration it is user_tickets_answers while you are querying user_ticket_answers table in database.

Try to change the statements if it works, because it works for me when I had this error previously. To be sure, check again the Documentation in passing custom key like

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


In UserTickets model change

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

to

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


In UserTicketAnswers

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

to

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


same logic with your User model.

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

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


Add each to UserTickets and UserTicketAnswers model

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