【发布时间】:2019-03-13 01:02:52
【问题描述】:
使用 Laravel 5.7。
设计一个包含许多视图的应用程序。
在这种情况下:
- 有一个(只有一个)client_id 字段。这是隐藏的,值是从 url 段中检索的。
- 其他字段是动态的(日期、类型、cmets)并且是指该客户购买的一种或多种产品。
我不知道如何将输入值从动态字段保存到数据库中(对不起,我我对编码很陌生)
请参阅下面我当前的代码和尝试。
我发现堆栈溢出中的相关答案无法使它们适合我的情况。
我会很感激帮助
控制器中的 STORE() 函数
public function storeDYNarray(Request $request)
{
$client = $request->input('client_id');
$all = $request->input();
$products = $request->input('product');
//dd($all); SEE BELOW
//THIS CREATES AS MANY NEW ENTRIES IN PRODUCTS TABLE AS NEEDED WITH THE CORRESPONDING client_ID
foreach ($products as $product){
$dia = new Product;
//client_id is retrieved from an URL segment
$dia->client_id = $request->input('client_id');
//DON'T KNOW HOW TO SAVE VALUES FROM THE DYNAMIC FIELDS
$dia->save();
}
我最好的镜头(很多不值得展示)
public function storeDYNarray(Request $request)
{
$client = $request->input('client_id');
$all = $request->input();
$products = $request->input('product');
$i=1;
$client_products[$i] = array();
foreach ($products as $product){
while ($i<=count($products)){
$client_products[$i] = new Product(array(
'client_id' => $client,
'product_date' => $products[$i]['date'],
'product_type' => $products[$i]['type'],
'product_comment' => $products[$i]['comment'],
));
$client_products[$i]->save();
}
}
}
}
//this returns Undefined index errors
返回 dd($all);输出
array:3 [▼
"_token" => "uvtLaCiuAueBIuyWkoCoOTdQzYB1paxhnLw0lbyO"
"client_id" => "898"
"product" => array:2 [▼
1 => array:3 [▼
"date" => "2019-03-13"
"type" => "new"
"comment" => "surplus"
]
2 => array:3 [▼
"date" => "2019-03-28"
"type" => "used"
"comment" => "good condition"
]
]
]
产品表
class CreateProductsTable extends Migration
{
public function up()
{
//KEPT VALIDATION PARAMETERS SIMPLE FOR KNOW
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('client_id')->nullable($value = true);
$table->date('product_date')->nullable($value = true);
$table->string('product_type')->nullable($value = true);
$table->longText('comment_about_product')->nullable($value = true);
$table->timestamps();
});
}
产品型号
class product extends Model
{
//GIVEN THE STRUCTURE OF ARRAYS WHEN dd($all); I DONT THINK I NEED THAT
/*
public $fillable = [
'client_id',
'product_date',
'product_type',
'product_comment',
];
*/
public function client(){
return $this->belongsTo('App\client');
}
}
客户表
<?php
//use Illuminate...
class CreateclientsTable extends Migration
{
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->string('client_id');
$table->primary('client_id');
//other columns...
$table->integer('user_id')->nullable($value = true);
$table->timestamps();
});
}
客户模型
class client extends Model
{
protected $primaryKey = 'client_id';
public $incrementing = false;
protected $keyType = 'string';
public function user(){
return $this->belongsTo('App\User');
}
public function products(){
return $this->hasMany('App\product');
}
}
【问题讨论】: