douningchang3610 2018-07-01 09:22
浏览 142
已采纳

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);
    }
}
  • 写回答

2条回答 默认 最新

  • doubingguan3425 2018-07-01 09:45
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 爬取豆瓣电影相关处理
  • ¥15 手机淘宝抓清除消息接口
  • ¥15 C#无selenium
  • ¥15 LD衰减计算的结果过大
  • ¥15 用机器学习方法帮助保险公司预测哪些是欺诈行为
  • ¥15 计算300m以内的LD衰减
  • ¥15 数据爬取,python
  • ¥15 怎么看 cst中一个面的功率分布图,请说明详细步骤。类似下图
  • ¥15 为什么我的pycharm无法用pyqt6的QtWebEngine
  • ¥15 FOR循环语句显示查询超过300S错误怎么办