首页 > 解决方案 > Laravel where in a relational database

问题描述

I have two tables Thread and Participants Thread has many participants and I'm able to access it like so:

Thread::with('participants')->get();

The participants table has a column last_read I would like to get all participants from thread WHERE last_read is NULL. I've tried this but it returns an error.

Thread::with('participants')
                          ->where('last_read', NULL)
                          ->get();

I am getting this error:

ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'last_read' in 'where clause' (SQL: select * from threads where last_read is null and threads.deleted_at is null)

Any idea how I can do this?

标签: laravel

解决方案


Since you want a query on relation table use whereHas

Thread::with('participants')
    ->whereHas('participants', function($q){
         $q->where('last_read', NULL);
    })->get();

推荐阅读