Query by user id

Hello,

I need help, please.

Basically I want to show, to the current logged "user id", all his records in a table. In this table were saved many records, all of these containing the "user id" field, populated with BlameableBehavior function.

Sorry for trivial question, but where I must put the query? In the actionindex, in the actionview or in other part of the controller ? Can you show an example?

These are my actual actionindex and actionview (if i must write here my code)


    public function actionIndex()

    {

        $searchModel = new UmarSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }


    /**

     * Displays a single Umar model.

     * @param string $id

     * @return mixed

     */

    public function actionView($id)

    {

        return $this->render('view', [

            'model' => $this->findModel($id),

        ]);

    }



Do you want to have special controller that is responsible for displaying user data ? For example, in your menu you have option like: "Profile" and when user clicks on it, Profile controller will display all data for the currently logged in user ?

In that case you can write query in index action of Profile controller. So you just have to write query that will get all data where user_id is equal to the id of the currently logged in user.

Like:


where(['user_id' => Yii::$app->user->id])

Yes, I need exactly this. But can you be so kindly to show to me how to implement where condition in the default controller?




    public function actionIndex()

    {

        $searchModel = new UmarSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }



Open your UmarSearch model, and in search() method, change this code:


$query = Umar::find();

to:




$query = Umar::find()->where(['user_id' => Yii::$app->user->id]);



I think that should do it.

Perfect, works. Thank you very much. I did not realize was must run. It is now clear.

I read this Query Builder and Query, but I could not figure out where to take action.

No problem.

Well you are using Search model, so you have to customize your query there. It really depends where your data provider is geting data from. If you do not use Search model, it may be some normal model, or in many cases you would write your query directly in controller action.