Laravel 多对多关系与自定义表名和 ID

Nee*_*eko 5 migration entity-relationship many-to-many laravel

您好,我在问题 [表名:tblquestion,id:que_id ] 和 Agecategory [表名: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); => 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

年龄类别模型

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

问题年龄类别模型

class QuestionAgecategory extends Model
{
    protected $table = 'tblquestionagecategory';
    protected $primaryKey = 'qac_id';
    protected $keyType = 'integer'; 
    public $incrementing = true;
}
Run Code Online (Sandbox Code Playgroud)

迁移

      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');
      });
Run Code Online (Sandbox Code Playgroud)

Eru*_*iel 11

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

你属于许多人期待一个tblquestion_tblagecategory不存在的数据透视表。正如先前的回答所述,您应该更改您的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');
}
Run Code Online (Sandbox Code Playgroud)

而且,在您的其他年龄类别模型中

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