Laravel 筛选关系数据

Laravel filter relationship data

代码

public function getCauserDetails(){
   return $this->belongsTo(Users::class, 'causer_id', 'id');
}

$name = testtt; //data to find

ActivityLog::where('causer_id', $userid)
    ->orWhere('subject_id', $userid)
    ->with('getCauserDetails')
    ->whereHas('getCauserDetails', function ($q) use ($name) {
        $q->where('name', "=", 'testtt');
    })
    ->get()
    ->toArray();

数据return

Array
(
    [0] => Array
        (
            [id] => 22
            [log_name] => login
            [subject_type] => App\Models\Users
            [subject_id] => 0
            [causer_id] => 2
            [created_at] => 2021-05-18 21:27:07
            [updated_at] => 2021-05-18 21:27:07
            [get_causer_details] => Array
                (
                    [id] => 2
                    [name] => lim
                )
        )

    [1] => Array
        (
            [id] => 21
            [log_name] => logout
            [subject_type] => App\Models\Users
            [subject_id] => 0
            [causer_id] => 2
            [created_at] => 2021-05-18 21:26:57
            [updated_at] => 2021-05-18 21:26:57
            [get_causer_details] => Array
                (
                    [id] => 2
                    [name] => Senior
                )

        )

    [2] => Array
        (
            [id] => 22
            [log_name] => logout
            [subject_type] => App\Models\Users
            [subject_id] => 0
            [causer_id] => 2
            [created_at] => 2021-05-18 21:26:57
            [updated_at] => 2021-05-18 21:26:57
            [get_causer_details] => Array
                (
                    [id] => 2
                    [name] => testtt
                )

        )
)

问题: 我试图过滤数据,如果关系“getCauserDetails”,如果只找到关系名称“test”,我怎么能不显示数据,或者我应该说空?因此在示例输出中,它显示了所有数据,但我只想检索我筛选的数据。

因为你的orWhere()你需要嵌套它:

$name = 'testtt'; //data to find

ActivityLog::with('getCauserDetails')
    ->where(function($q) {
        $q->where('causer_id', $userid)
        ->orWhere('subject_id', $userid)
    })
    ->whereHas('getCauserDetails', function ($q) use ($name) {
        $q->where('name', "=", $name);
    })
    ->get()
    ->toArray();

您也可以过滤关系:

$name = 'testtt'; //data to find
ActivityLog::where('causer_id', $userid)
    ->orWhere('subject_id', $userid)
    ->with(['getCauserDetails' => function ($q) use ($name) {
        $q->where('name', "=", $name);
    }])
    ->whereHas('getCauserDetails', function ($q) use ($name) {
        $q->where('name', "=", $name);
    })
    ->get()
    ->toArray();