Search code examples
phpdatabaseyii2message

How to get data from database by parameters in yii2?


I have 2 database tables:

user

id | name,

message

id | sender_id | receiver_id.

How can I generate custom view and get data by sender_id and receiver_id? I mean when user log in he will see his inbox and outbox messages. Please explain the logic of this. I also will be glad if you will provide code examples because I am newbie in php and yii2. If something is not understandable I will explain more specifically.


Solution

  • You are really short on details, but I assume you want to display both incoming and sent messages by matching current user ID (logged in user) with both receiver_id and sender_id and display them in a gridview.

    An approach could be:

    public function actionIndex()
    {
        $user = Yii::$app->user->identity;
    
        $searchModel = new MesssageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
        // filter on ownership of either sender or receiver
        $dataProvider
            ->query
            ->andWhere(['receiver_id' => $user->id])
            ->orWhere(['sender_id' => $user->id]);
    
        $dataProvider->setSort([
            'defaultOrder' => ['created_at' => SORT_DESC],
        ]);
    
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    

    This assumes you have limited access to logged-in users otherwise you need to catch the case when Yii::$app->user is null.