关联模型查询时,加上select,with返回的就是null,不加select,才能返回数据

数据库:

store表:
id,store_group_id, ...

channel表:
id, channel_name, ...

模型代码:

Store.php Store模型:
public function channel()
{
    return $this->belongsTo(StoreChannel::class, 'store_group_id');
}

控制器代码:

$stores = Store::where($where)
    ->with('channel')
    ->select('store_name')  // 当加上这个的时候,with('channel')返回的就是null
    ->paginate($page_size)
    ->toArray();

结果:
加了->select('store_name')

        "data": [
            {
                "store_name": "suscipit",
                "channel": null
            },
            {
                "store_name": "at",
                "channel": null
            }
        ]

不加->select('store_name')

        "data": [
            {
                "id": 16,
                "business_no": "111111",
                "store_no": "1903",
                "brand": "sit",
                "store_code": "1740",
                "store_name": "suscipit",
                "store_group_id": 2,
                "channel": {
                    "id": 2,
                    "channel_name": "石家庄金平区",
                }
            },
            {
                "id": 25,
                "business_no": "111111",
                "store_no": "4591",
                "brand": "voluptatum",
                "store_code": "4974",
                "store_name": "at",
                "store_group_id": 2,
                "channel": {
                    "id": 2,
                    "channel_name": "石家庄金平区",
                }
            }
        ]
Nixus
修改的评论也不能少于六个字哦!