在Yi2中查询并在另一个表中检查关系

时间:2018-10-31 16:18:29

标签: php yii2

我正在尝试在Yii2表调用Post中获取数据。该表具有属性调用所有者,我想检查所有者的值是否等于特定的值,我通过将其称为userId或所有者的值等于Followship表的以下属性,其中follower属性的值Followship Table的值等于我传递的值userId。 在逻辑上一点一点地实现上面的代码时,我编写了以下代码;

     $allpost  = Post::find()->all();
     $relevantpost = [];
     foreach ($allpost as $post) {
        if($post->owner == $userId){
            $relevantpost[] = $post;
        }
        else{
            $follower = Followship::findOne(['follower'=>$userId, 'following'=>$post->owner]);
            if($follower){
                $relevantpost[] = $post;
            }
        }
     }
     return $relevantpost;

此代码效果很好,但我想为此编写一个有效的查询;

$allpost  = Post::find()
                    ->where(['owner'=>$userId])
                    ->orWhere(['is NOT', $follower = Followship::findOne(['follower'=>$userId]) and 'owner' => $follower->following, NULL])
                    ->all();

或更糟的情况下

$allpost = \Yii::$app->db
            ->createCommand(
                "SELECT postId, location, details, created_at FROM Post
                     WHERE owner = " . $userId. "OR
                        owner = '0' OR
                        owner = following IN (
                            SELECT following FROM Followship WHERE follower = ". $userId . " AND 
                            )
                ORDER BY dateCreated DESC"    
            )
            ->queryAll();

我在上述查询中不断出错。我错过了Yii2查询构建器的基本知识。 请对此提供任何帮助。

2 个答案:

答案 0 :(得分:2)

首先,您可以在Post类中建立一个关系(通过帖子所有者连接Post和Followers)

 class Post extends ActiveRecord {

       public function getFollowersDataset() {
          return $this->hasMany(Followers::className(), ['following' => 'owner']);
       } 
    ...
    }

然后您可以在查询中使用它

Post::find()
       ->joinWith('followersDataset')
       ->where(['or', 
          ['owner' => $user_id],  
          ['follower' => $user_id]])
       ->all()

答案 1 :(得分:0)

条件接受三个参数 [the_condition, the_attribute, the_value]

ANDOR的情况下,情况发生了变化 [the_condition, first_condition, second_condition]

第二次尝试后,您可以做出类似的事情

$allpost  = Post::find()
    ->where(['owner'=>$userId])
    ->orWhere([
         'AND',
         ['is NOT', $follower, Followship::findOne(['follower'=>$userId]),
         ['owner', $follower->following, NULL]
     ])
     ->all();

您可以在调试栏中检查正在执行的查询,或者以其他方式在字段中出错,例如,如果在您的条件下放置了->where(['owners'=>$userId]),则该错误将与您所做的查询,这样您就可以查看您进行的查询