书
----------------------------
| id | name | published |
----------------------------
| 1 | book1 | 1 |
| 2 | book2 | 1 |
| 3 | book3 | 0 |
章
----------------------------
| id | book_id | name | published |
----------------------------
| 1 | 1 | chapter1 | 1 |
| 2 | 1 | chapter2 | 0 |
| 2 | 2 | chapter1 | 0 |
| 3 | 3 | chapter1 | 1 |
class Book{
public function getChapter()
{
return $this->hasMany(Chapter::className(), ['kook_id' => 'id']);
} }
class Chapter{
public function getBook()
{
return $this->hasOne(Book::className(), ['id' => 'book_id']);
} }
如何使用ActiveRecord获取已发布网页的已发布图书(我希望将book1与chapter1和book2一起使用,不带任何章节)?
像Book :: find($ id) - >其中(['published'=> 1]) - > {{{left join with where}}} - > all())
ADDED 然后我用魔杖来使用它
echo $book->name;
foreach($book->getChapter() as chapter){
echo chapter->name;
}
答案 0 :(得分:0)
将您的图书班级relation
更改为
class Book
{
public function getChapter()
{
return $this->hasMany(Chapter::className(), ['book_id' => 'id'])->where(['published' => 1]);
}
}
要获取相关记录,请使用with()
Book::find()->with(['chapter'])->where(['id' => $id ,'published' => 1])->all()
使用它:
//Book Name
echo $book->name;
//For Chapters Name
if($book->chapter){
foreach($book->chapter as $chapter){
echo $chapter->name;
}
}