您好,因此我在Question [表名: tblquestion ,id: que_id ]和Agecategory [表名: tblagecategory >,id: aca_id ]。他们共享了名为QuestionAgecategory的表[表名: tblquestionagecategory ,ID: qac_id ]。
我想指出的是,所有IDS和表名都是自定义名称,而不是按照典型的Laravel语法。
我正试图在Laravel中将它们联系起来。到目前为止,当我尝试查看$ question-> agecategories时,它返回null;
$ question->分类; =>空
但是它中有记录,并在$ 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');
}
}
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');
});
答案 0 :(得分:2)
您正在使用自定义列和自定义数据库命名。
您属于许多人,期待透视表tblquestion_tblagecategory
不存在。正如previos的回答所述,您应该更改自己的belongsToMany以搜索自定义表和列。
https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
在您的问题模型中更改为此
public function agecategories()
{
return $this->belongsToMany('App\Agecategory', 'tblquestionagecategory', 'qac_que_id', 'qac_aca_id');
}
而且,在您的其他Agecategory模型中
public function questions()
{
return $this->belongsToMany('App\Question', 'tblquestionagecategory', 'qac_aca_id', 'qac_que_id');
}
答案 1 :(得分:0)
在问题模型中添加以下关系函数
public function agecategories()
{
return $this->belongsToMany('App\Agecategory', 'tblquestionagecategory', 'qac_que_id', 'qac_aca_id');
}
答案 2 :(得分:0)
我遇到了同样的问题,但是我只能声明没有这样的前缀的外键:
public function agecategories()
{
return $this->belongsToMany('App\Agecategory', 'tblquestionagecategory', 'que_id', 'aca_id');
}