Yii2 get data using hasMany relation

208
May 17, 2017, at 1:08 PM

I have a query $occupier that get all the ID (10 & 16) from the table. The problem is how should I put it in the activeDataProvider query so that I can get all the ID that pass on since I cant do foreach loop inside the query.

Relation:

public function getop_occupier()
    {
        return $this->hasMany(OpOccupier::classname(),['id'=>'unit_id']);
    }

Controller:

$occupier = OpOccupier::find()
                ->where(['unit_id'=>$id])
                ->all();

$dataProviderTranscation = new ActiveDataProvider([
'query' => OpOccupierTrxGroup::find()->where(['or','occupier_id'=>10,'occupier_id'=>16]),]);

I tried:

$dataProviderTranscation = new ActiveDataProvider([
    'query' => OpOccupierTrxGroup::find()->where(['occupier_id'=>$occupier['id'])->all();

It return error UNDEFINED INDEX ID.

Any help or advice would be appreciated. Thanks

Answer 1

You can use to lefJoin relation for joining table

$dataProviderTranscation = 
 new ActiveDataProvider([
'query' => 
      OpOccupierTrxGroup::find()
       ->where(['op_occupier'=>$occupier['id'])
       ->andWhere(['occupier.id'=>[10,16]])
       ->leftJoin('occupier','occupier.id=op_occupier_trx_group.occupier_id')
       ->all();
READ ALSO
PHP/SQL - PHP won't output sql query

PHP/SQL - PHP won't output sql query

could you please help me? just trying to fill in some text as stackoverflow wants to write more text because it's all code

77
How to get unread notifications (2 tables with FK)

How to get unread notifications (2 tables with FK)

I have 2 tables on my DB: user_notification and user_notification_readIt's a user notification system, the notifications are on user_notification and when a user reads a notification, it stores on user_notification_read with the notification id and the user id

114
Files not storing in the correct folder

Files not storing in the correct folder

I created a page that can add new records to my database, everything is working fine but when I'm trying to upload a pdf file, it doesn't store to the correct folderIt should be stored in my "uploads"

62