计算其他 2 个急切列的新列 Laravel
New column from calculating 2 other eager columns Laravel
我在 Eloquent 查询结果中得到 2 个通过 withCount
生成的号码。有没有办法 multiply/divide/add 这 2 个数字并创建一个新字段?
$data = Trek::select('name')
->withCount('past_bookings')
->withCount('bookings')
->get();
(喜欢->select(DB::raw('past_bookings*bookings as new_col'))
??)
当我使用访问器时,出现 Call to a member function addEagerConstraints() on int
错误。
您也可以通过其他步骤完成。像这样:
$collection = Trek::select('name')
->withCount('past_bookings')
->withCount('bookings')
->get();
$data = [];
foreach($collection as $item) {
$data['past_bookings_count/bookings as new_col'] = ($item['past_bookings'] / $item['bookings_count']);
}
dd($data);
但是,如果将其传递给视图,我将离开循环并在视图中执行计算。
.blade.php
{{ $data['past_bookings_count'] / $data['bookings_count'] }}
您真的需要新专栏吗?你可以在你的模型上做;
protected $appends = ['my_calculation'];
public function getMyCalculationAttribute()
{
return $this->past_bookings_count * $this->bookings_count;
}
您可以这样访问它:
$trekModel->my_calculation;
你可以看看official docs
我在 Eloquent 查询结果中得到 2 个通过 withCount
生成的号码。有没有办法 multiply/divide/add 这 2 个数字并创建一个新字段?
$data = Trek::select('name')
->withCount('past_bookings')
->withCount('bookings')
->get();
(喜欢->select(DB::raw('past_bookings*bookings as new_col'))
??)
当我使用访问器时,出现 Call to a member function addEagerConstraints() on int
错误。
您也可以通过其他步骤完成。像这样:
$collection = Trek::select('name')
->withCount('past_bookings')
->withCount('bookings')
->get();
$data = [];
foreach($collection as $item) {
$data['past_bookings_count/bookings as new_col'] = ($item['past_bookings'] / $item['bookings_count']);
}
dd($data);
但是,如果将其传递给视图,我将离开循环并在视图中执行计算。
.blade.php
{{ $data['past_bookings_count'] / $data['bookings_count'] }}
您真的需要新专栏吗?你可以在你的模型上做;
protected $appends = ['my_calculation'];
public function getMyCalculationAttribute()
{
return $this->past_bookings_count * $this->bookings_count;
}
您可以这样访问它:
$trekModel->my_calculation;
你可以看看official docs