簡體   English   中英

在yii2中使用多個表的連接

[英]use Joins for multiple tables in yii2

我正在使用yii2,我有3個表:帖子,粉絲,評論,我想使用joinWith()來獲取帖子及其評論和粉絲名稱(在粉絲表中)以供發布和評論。 我寫的是這個查詢:

<pre>
 facebook_posts::find()->joinwith('fans')->joinWith('comments')->all();
</pre>

我為關系添加了這兩個函數:

<pre>
    public function getfans() {
        return $this->hasOne(Fans::className(), ['id' => 'from_id'])->from(fans::tableName() . ' FBF');
    }
    public function getComments() {
        return $this->hasMany(Comments::className(), ['parent_id' => 'id'])->from(comments::tableName() . ' FBC');
    }
</pre>

這給了我寫帖子及其評論的粉絲的帖子和數據,但我需要的是粉絲的數據也寫了評論,所以如何加入評論與粉絲表?

確保您的Comments模型中有fan關系,然后您可以使用以下內容獲取每個帖子的所有評論以及每條評論的粉絲關系:

facebook_posts::find()->joinWith('fans')->joinWith(['comments', 'comments.fan'])->all();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM