【问题标题】:Eloquent multiple rows insert and in one array loop雄辩的多行插入并在一个数组循环中
【发布时间】:2018-02-02 17:03:54
【问题描述】:

我的用户输入遵循以下规则;

public function rules()
    {
        return [
            'phone_number' => 'required|array',
            'amount' => 'required|string|max:4',
            'phone_number_debit' => 'required|string|max:15',
        ];
    }

我想将数据保存在模型Transaction 中。对于phone_number,它是一个可以有一个值或多个值的数组。这样就剩下 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();

根据phone_number数组中的记录保存不同的记录。

但是我想不出一种方法来实现这一点。

有人吗?

【问题讨论】:

  • 你能为每个phone_number元素创建一个条目吗?
  • @IanRodrigues 我该如何做到这一点?该数组与其他数组在同一个请求中。
  • 为什么不创建子表呢?一笔交易会有很多电话号码。它会更容易管理。
  • 顺便说一句,您在示例中拼写事务错误

标签: php laravel eloquent laravel-5.3


【解决方案1】:

简而言之,有很多方法可以做到这一点:

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;DR

一对多关系

为了得到更好的代码,可以创建transaction_phones表,创建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();
});

在您的 Transaction 模型中,您将得到相反的结果:

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);
});

希望这个回答对你有帮助。

【讨论】:

    【解决方案2】:

    试试这个:

    $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']
        ]);
    }
    

    确保在您的 Trasaction 模态中您已设置为这样的可填充属性:

    class Trasaction extends Model 
    {
        protected $fillable = ['amount', 'phone_number', 'phone_number_debit'];
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-03
      • 2016-06-24
      • 2017-06-26
      • 1970-01-01
      • 2017-03-31
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多