Hello so I have many to many relation between Question [table name: tblquestion, id: que_id] and Agecategory [table name: tblagecategory, id: aca_id]. They have shared table named QuestionAgecategory [table name: tblquestionagecategory, id: qac_id].
I want to note that all the IDS and table names are custom named and not according to typical Laravel syntax.
And I am trying to relate them in Laravel. So far it returns null when I try to look $question->agecategories;
$question->agecategories; => null
But it has records in it and returns this after $question = App\Question::find(1);
$question = App\Question::find(1); => App\Question {#2901 que_id: 1, que_name: "hello",
Question model
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');
}
}
Agecategory model
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 model
class QuestionAgecategory extends Model
{
protected $table = 'tblquestionagecategory';
protected $primaryKey = 'qac_id';
protected $keyType = 'integer';
public $incrementing = true;
}
Migrations
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');
});
tblquestion
.*,agecategory_question
.agecategory_aca_id
aspivot_agecategory_aca_id
,agecategory_question
.question_que_id
aspivot_question_que_id
fromtblquestion
inner joinagecategory_question
ontblquestion
.que_id
=agecategory_question
.question_que_id
whereagecategory_question
.agecategory_aca_id
= 1)' – Mauney