2016-06-23 71 views
0

圖書加入Yii2 AR留下的位置和關係

---------------------------- 
| 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發佈的網頁書(我想獲得與第一章和Book BOOK1沒有任何章節)?

水木清華像書::發現($ ID) - >在哪裏([ '出版'=> 1) - > {{{左連接與在}}} - >所有())

ADDED 然後我的魔杖使用它

echo $book->name; 
foreach($book->getChapter() as chapter){ 
    echo chapter->name; 
} 

回答

0

更改Book類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; 
    } 
} 
+0

以及如何使用它(看我的問題加入)? – yeryr

+0

太棒了!它可以很好地工作 – yeryr