PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 12, 2022

[FIXED] How to get data from database by parameters in yii2?

 July 12, 2022     database, message, php, yii2     No comments   

Issue

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.



Answered By - jlapoutre
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing