Php 雄辩的多行插入和一个数组循环
我有以下规则的用户输入Php 雄辩的多行插入和一个数组循环,php,laravel,eloquent,laravel-5.3,Php,Laravel,Eloquent,Laravel 5.3,我有以下规则的用户输入 public function rules() { return [ 'phone_number' => 'required|array', 'amount' => 'required|string|max:4', 'phone_number_debit' => 'required|string|max:15', ]; } 我想将数据
public function rules()
{
return [
'phone_number' => 'required|array',
'amount' => 'required|string|max:4',
'phone_number_debit' => 'required|string|max:15',
];
}
我想将数据保存在模型事务中
。对于电话号码,它是一个数组,可以有一个值或多个值。这样就剩下foreach循环了
这就是我想要实现的,保存由数组中记录数决定的不同行
$transaction = new Trasaction();
$transaction->phone_number = $req->phone_number; //Value in the array
$transaction->amount = $req->amount;
$transaction->phone_number_debit = $req->phone_number_debit;
$transaction->save();
根据电话号码数组中的记录保存不同的记录
然而,我想不出一个办法来实现这一点
有人吗?简单地说,有很多方法可以做到这一点:
collect(request('phone_number'))->each(function ($phone) use ($req) {
$transaction = new Trasaction();
$transaction->phone_number = $phone; // element of the array
$transaction->amount = $req->amount;
$transaction->phone_number_debit = $req->phone_number_debit;
$transaction->save();
});
TL;博士
一对多关系
为了获得更好的代码,您可以创建一个transaction\u
表,创建一个one-to-many
关系
您将创建一个TransactionPhone
模型并添加以下内容:
public function transaction()
{
return $this->belongsTo(Transaction::class);
}
TransactionPhone
迁移:
Schema::create('transaction_phones', function (Blueprint $table) {
$table->increments('id');
$table->integer('transaction_id');
$table->string('phone_number');
$table->timestamps();
});
在您的事务
模型中,您将得到相反的结果:
public function phones()
{
return $this->hasMany(TransactionPhone::class);
}
public function addPhone($phone)
{
return $this->phones()->create(['phone_number' => $phone]);
}
在您的控制器中:
$transaction = Trasaction::create(request()->only('amount', 'phone_number_debit'));
collect(request('phone_number'))->each(function ($phone) use ($transaction) {
$transaction->addPhone($phone);
});
我希望这个答案能对你有所帮助。试试这个:
$data = request(['amount', 'phone_number', 'phone_number_debit']);
foreach($data['phone_number'] as $phone_number) {
Trasaction::create([
'amount' => $data['amout'],
'phone_number' => $phone_number,
'phone_number_debit' => $data['phone_number_debit']
]);
}
确保在您的传输操作中
模式已设置为可填充属性,如下所示:
class Trasaction extends Model
{
protected $fillable = ['amount', 'phone_number', 'phone_number_debit'];
}
你能为每个
电话号码元素创建一个条目吗?@IanRodrigues我如何做到这一点?该数组与其他数组处于相同的请求中。为什么不创建一个子表呢?一笔交易会有很多电话号码。这将使它更易于管理。顺便说一句,您在示例中将事务拼写错误