dongyingla8668 2016-08-03 09:23
浏览 208
已采纳

如何通过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.

  • 写回答

1条回答 默认 最新

  • dp7311 2016-08-04 12:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题