【发布时间】:2019-01-29 15:07:14
【问题描述】:
你好,所以我在 Question [table name: tblquestion, id: que_id] 和 Agecategory [table name: tblagecategory 之间有多对多的关系>,id:aca_id]。他们共享名为 QuestionAgecategory 的表 [表名:tblquestionagecategory,id:qac_id]。
我想注意的是,所有的 IDS 和表名都是自定义命名的,而不是根据典型的 Laravel 语法。
我正在尝试在 Laravel 中关联它们。到目前为止,当我尝试查看 $question->agecategories;
时它返回 null$question->agecategories; => 空
但是它里面有记录,并且在 $question = App\Question::find(1); 之后返回这个
$question = App\Question::find(1); => 应用\问题{#2901 que_id: 1, que_name: "你好",
问题模型
class Question extends Model
{
protected $table = 'tblquestion';
protected $primaryKey = 'que_id';
protected $keyType = 'integer';
public $incrementing = true;
public $timestamps = false;
public function agecategories()
{
return $this->belongsToMany('App\Agecategory');
}
}
年龄分类模型
class Agecategory extends Model
{
protected $table = 'tblagecategory';
protected $primaryKey = 'aca_id';
protected $keyType = 'integer';
public $incrementing = true;
public function questions()
{
return $this->belongsToMany('App\Question');
}
}
QuestionAgecategory 模型
class QuestionAgecategory extends Model
{
protected $table = 'tblquestionagecategory';
protected $primaryKey = 'qac_id';
protected $keyType = 'integer';
public $incrementing = true;
}
迁移
Schema::create('tblquestion', function (Blueprint $table) {
$table->increments('que_id');
$table->string('que_name', 128);
});
Schema::create('tblagecategory', function (Blueprint $table) {
$table->increments('aca_id');
$table->timestamps();
});
Schema::create('tblquestionagecategory', function (Blueprint $table) {
$table->increments('qac_id');
$table->integer('qac_que_id')->unsigned();
$table->integer('qac_aca_id')->unsigned();
$table->foreign('qac_que_id')->references('que_id')->on('tblquestion');
$table->foreign('qac_aca_id')->references('aca_id')->on('tblagecategory');
});
【问题讨论】:
标签: laravel migration many-to-many entity-relationship