PDA

View Full Version : ایجاد رابطه چند به چند



desatir7316
چهارشنبه 26 فروردین 1394, 09:40 صبح
سلام دوستان
من این جدول ها رو دارم :


$this->createTable('category', [

'id' => Schema::TYPE_PK,

]);


$this->createTable('question', [

'id' => Schema::TYPE_PK,

'recall' => Schema::TYPE_INTEGER,

'standard' => Schema::TYPE_INTEGER,

]);


$this->createTable('category_relation', [

'id' => Schema::TYPE_PK,

'category_id' => Schema::TYPE_INTEGER,

'post_id' => Schema::TYPE_INTEGER,

'type' => Schema::TYPE_STRING,

]);



$this->addForeignKey('category_ralation_to_category', 'category_relation', 'category_id', 'category', 'id', 'CASCADE', 'CASCADE');

$this->addForeignKey('category_relation_to_question', 'category_relation', 'post_id', 'question', 'id', 'CASCADE', 'CASCADE');




توی مدل Category هم این رابطه رو ایجاد کردم:


public function getQuestions(){

return $this->hasMany(Question::className(), ['id' => 'post_id'])

->viaTable(CategoryRelation::tableName(), ['category_id' => 'id']);

}

الان اون اطلاعاتی رو که می خوام رو بر می گردونه، مثال :


Category::findOne(34)->questions


حالا چطوری می تونم یه سری شرط بهش اضافه کنم مثل اینکه فقط اون رکورد هایی رو بیار که توی جدول category_relation یه مقدار خاص برای فیلد type هست و اینکه توی جدول question مقدار recall برابر 1 هست

ممنون