Laravel 与自定义 table 名称和 ID 的多对多关系

Laravel many-to-many relation with custom table names and IDs

你好所以我在问题 [table name: tblquestion, id: que_id[=41 之间有多对多关系=]] 和年龄类别 [table 名称:tblagecategory,ID:aca_id]。他们共享了 table 名为 QuestionAgecategory [table name: tblquestionagecategory, id: qac_id]。

我要注意所有 IDS 和 table 名称都是自定义命名的,而不是根据典型的 Laravel 语法。

我正试图在 Laravel 中将它们联系起来。到目前为止,当我尝试查看 $question->agecategories;

时,它 returns null

$question->agecategories; => null

但是它里面有记录而且 returns 这个在 $question = App\Question::find(1);

之后

$question = App\Question::find(1); => App\Question {#2901 que_id: 1, que_name: "hello",

问题模型

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

在问题模型中添加以下关系函数

public function agecategories() 
{
    return $this->belongsToMany('App\Agecategory', 'tblquestionagecategory', 'qac_que_id', 'qac_aca_id');
}

您正在使用自定义列和自定义数据库命名。

Your Belongs to many 期待一个不存在的支点 table tblquestion_tblagecategory。正如前面的回答所述,您应该更改 belongsToMany 以搜索自定义 table 和列。

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

还有,在您的其他年龄类别模型中

public function questions() 
{
    return $this->belongsToMany('App\Question', 'tblquestionagecategory', 'qac_aca_id', 'qac_que_id');
}

我遇到了同样的问题,但我不得不像这样只声明没有前缀的外键:

public function agecategories() 
{
    return $this->belongsToMany('App\Agecategory', 'tblquestionagecategory', 'que_id', 'aca_id');
}