我有一个名为UserCommission的数据库表,下面为我做了一个雄辩的模型:
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCommission extends Model
{
protected $connection = 'sqlsrv';
protected $table = 'UserCommission';
}
现在在控制器中,我有很多要添加到该表中的信息。我首先将其放入如下所示的集合中:
$returnData = new Collection();
foreach ($datePeriod as $key => $date)
{
foreach ($consultants as $consultant)
{
$year = (int) $date->format('Y');
$month = (int) $date->format('n');
$commission = new UserCommission();
$commission->userId = $consultant['UserId'];
$commission->year = $year;
$commission->month = $month;
$commission->commissionPercentage = Self::getCommissionPercentage($consultant['UserId'], $consultant['CreatedOn'], $consultant['RoleId'], $date);
$returnData->push($commission);
}
}
因此,当我打印出返回数据时,它将打印出一个集合,该集合中填充了正确的项及其属性,以与表格字段匹配。我找不到如何将其保存到表中。
我尝试过
$returnData->save();
但这不是收集功能。
答案 0 :(得分:1)
如果要避免一次又一次进行多次插入(因此避免了由于连续查询而导致的数据库性能问题),也可以使用Model::insert()
有关示例,请参见https://implode.io/inf5OO。
根据以下评论,请注意,他的方法不会为插入的记录触发雄辩的事件……
答案 1 :(得分:0)
您需要做
$user_commission = new UserCommission;
#Do Stuff
$user_commission->save();
答案 2 :(得分:0)
如果您想一次全部插入它们,则可以绕过Collection来代替:
$commissions = [];
foreach ($datePeriod as $key => $date)
{
foreach ($consultants as $consultant)
{
$year = (int) $date->format('Y');
$month = (int) $date->format('n');
$commissions[] = [
'userId' => $consultant['UserId'];
'year' => $year,
'month' => $month
'commissionPercentage' => Self::getCommissionPercentage($consultant['UserId'], $consultant['CreatedOn'], $consultant['RoleId'], $date);
];
}
}
由于insert()
可以接受要插入的数据数组,因此现在可以进行以下操作:
UserCommission::insert($commissions);