将数组值插入到数据库laravel

Sid*_*Sid 4 php mysql arrays laravel-5

我有一个表格属性调用namedescriptionfeatures在那里features是一个多个复选框这就好比

feature 1
feature 2
feature 2
feature 4
Run Code Online (Sandbox Code Playgroud)

用户可以一次选择多个复选框。我有一个名为product像的数据库表

-----------------------------------------
    id    name    description    features  
-----------------------------------------
Run Code Online (Sandbox Code Playgroud)

当用户选择多个复选框时,我需要在功能列中插入所有复选框值。现在我可以echo选择选中的复选框值,例如

 $feat = Input::get('features');
    foreach ($feat as $key => $n){
     echo $feat[$n];
    }
Run Code Online (Sandbox Code Playgroud)

但是我需要将这些功能插入到数据库中,对于正常插入,我们会这样做:

$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->features = Input::get('features');
$product->save();
Run Code Online (Sandbox Code Playgroud)

但是我应该如何修改上面的代码以将数组值保存到数据库中?我试图将值插入同一列,因为我不会根据功能查询它。

Qua*_*unk 6

这很简单。如果您知道您不会查询这些功能,那么将它们存储为 Json 或序列化数组就完全没问题了。但是如果您需要查询它们并且它们是您的应用程序的一个关键方面,您应该将它们放在它们自己的表中。

我更喜欢以 Json 格式存储数组,因为它更易于阅读并且不特定于 PHP。Laravel 为您提供了非常不错的选择来完成这项工作。

首先,在您的迁移中将您 -table的features-field声明products为 json:

Schema::create('products', function (Blueprint $table) {
    // ...
    $table->json('features');
});
Run Code Online (Sandbox Code Playgroud)

然后告诉您的Product-model在您访问它时自动将其转换为数组,只需设置一个$casts-attribute:

class Product extends Model
{
    // ...
    protected $casts = [
        'features' => 'json'
    ];
}
Run Code Online (Sandbox Code Playgroud)

就是这样。现在数组将存储为 Json,但是当您使用它访问它时,$product->features您将返回一个数组。

为了让一切变得更简单,你应该在你的 Product 模型上设置一个可填充的属性

class Product extends Model
{
    // ...
    protected $fillable = ['name', 'description', 'features'];
}
Run Code Online (Sandbox Code Playgroud)

这允许在您的控制器(或您创建产品的任何地方)中执行以下操作:

$product = Product::create(Input::all());
Run Code Online (Sandbox Code Playgroud)

...而不是更新它并一一设置属性。

并且如上所述,请确保您不需要可查询的功能,这意味着您不会遇到您试图获得仅具有特定功能或某些东西的某些产品的情况。但是如果你确实需要查找特征,你应该把它们放在它们自己的表中。否则这种方法很好,因为它更方便。