从Laravel-Eloquent对象获取数据


Get data from Laravel Eloquent object?

在传递到view/json之前,我想向Eloquent模型对象添加更多数据。

$company = Company::with("users")->get();

我想用$company再添加一些数据,我的尝试代码如下,

$company->data->client_count = User::where('status', '=', 1)->count();

但它不起作用,有什么解决方案吗?

如果要将数据添加到$company。您可以将其设为数组并传递值
$company[] = Company::with("users")->get();

$company[] = User::where('status', '=', 1)->count();

with方法接受一个数组。static Builder|Model with(array|string$relationships)意思是你可以说Model::with(['one','wo'])->get();

试试这个希望它能工作

$company['count'] = User::where('status', '=', 1)->count();

然后检查结果。