Eloquent 筛选关系记录

Eloquent filter relationship records

我只想从特定列不为空的关系中获取那些记录。以下是表格:

项目:
id name
1 item1
2 item2
零件数:
id item_id name
1 1 part1
2 1 part2
3 2 null
4 2 part3

Item 模型中的关系:

public function parts()
{
    return $this->hasMany('App\Models\Part');
}

Part 模型中的关系:

public function item()
{
    return $this->belongsTo('App\Models\Item');
}

我试过这个代码:

Item::with('parts')
    ->whereHas('parts', function($query) {
       $query->whereNotNull('name');
    })
    ->get();

并且它只检索 itemid = 1。我也想用 id = 2 得到 item,但只用 part,其中 name 不是 null

item2 分为两部分的问题

部分:

id item_id name
3 2 null
4 2 part3

您的查询 returns 部分(id:3 和 4)因为您正在查询:

Get me all the items with the parts, where items have part with a name.

但是你需要

Get me all the items with the parts that have a name, where the items have part with a name.

为此,您需要添加一个子查询

Item::with(['parts' => function($query) {
    $query->whereNotNull('name');
}])
    ->whereHas('parts', function($query) {
        return $query->whereNotNull('name');
    })
    ->get();