The same pit with and select in Laravel associated query

 Foreword:

        The principle of Laravel's associated query is to first find out the data of the model itself and the data of the associated model, and then perform associated queries through the defined primary key ID and foreign key ID.

        Therefore, the required fields of the data of the model itself when selecting must have the primary key ID (or custom associated fields) that define the association. Similarly, the required fields of the data of the associated model when selecting must also have the foreign key when defining the association ID (or custom associated field).

Therefore, the following writing method cannot query the user and avatar fields

// 获取评论列表数据,同时返回用户信息和头像信息
$comments = Comments::with(['user' => function($query) {
                $query->with(['avatar' => function($aq) {
                    $aq->select(['url']);
                }])->select(['nickname']);
}])->paginate($request->input('pagesize',10));

replaced by the following

// 获取评论列表数据,同时返回用户信息和头像信息
$comments = Comments::with(['user' => function($query) {
                $query->with(['avatar' => function($aq) {
                    $aq->select(['id','url']);
                }])->select(['id','nickname','avatar_id']);
}])->paginate($request->input('pagesize',10));

Guess you like

Origin blog.csdn.net/qq_27295403/article/details/122598069