Laravel关系被插入到集合中



我创建了以下访问器来检查代理属性:

public function getIsAgencyAttribute() {
// agency is a boolean value
return isset( $this->ref->agency ) && $this->ref->agency;
}
// relationship
public function ref() {
return $this->hasOne(SellerRef::class, 'user_id');
}
我调用append()方法:
$query = User::query();

// a bunch of when conditions...
// $query->when(...);  

$data = $query->limit( $request->limit ?: config('app.limit_per_page') )->get();
$data->append('is_agency');
return response()->json( responseFormat( false, $data ) );

预期响应:

{
"id": 5,
"name": "mariana",
"email": "mariana@email.com",
"blocked_at": null,
"deleted_at": null,
"created_at": "2021-03-05T02:44:46.000000Z",
"is_agency": false
}

当前响应:

{
"id": 5,
"name": "mariana",
"email": "mariana@email.com",
"blocked_at": null,
"deleted_at": null,
"created_at": "2021-03-05T02:44:46.000000Z",
"is_agency": false,
"ref": {
"user_id": 5,
"code": "OZO33T",
"agency": false
}
}

为什么ref属性被插入到集合中?如果去除$data->append('is_agency');,ref就会消失。

解决方案:

//change
public function getIsAgencyAttribute() {
return isset( $this->ref->agency ) && $this->ref->agency;
}
// to this
public function getIsAgencyAttribute() {
return isset( $this->ref()->first()->agency ) && $this->ref()->first()->agency;
}

相关内容

  • 没有找到相关文章

最新更新