在laravel存储库模式上插入相关表

时间:2016-01-04 07:11:56

标签: php laravel models

我有一个带有以下型号的产品和skus表

产品

class Product extends Model implements Transformable
{
    use TransformableTrait;
    protected $table      = 'products';
    protected $primaryKey = 'products_id';
    protected $fillable = ['user_profiles_id','is_app_ignored','product_name','product_description','tags','categories_id','image_count','is_active','is_shippable','creation_channels_id','is_admin_approved','users_id'];

    function skus()
    {
        return $this->hasMany('App\Entities\Sku','products_id');
    }
}

的SKU

<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class Sku extends Model implements Transformable
{
    use TransformableTrait;
    protected $table      = 'skus';
    protected $primaryKey = 'skus_id';
    protected $fillable = ['products_id','quantity','actual_price','selling_price','quantity_sold','quantity_type','quantity_total','bucket_value','currency','condition','sort_order'];

    function product()
    {
        return $this->hasMany('App\Entities\Product','products_id');
    }
}

这是需要插入的数据

[categories_id] => 1
    [product_name] => Pen
    [product_description] => this is a pen
    [tags] => pn,write
    [image_count] => 4
    [product_code] => ABCD
    [is_app_ignored] => y
    [creation_channels_id] => 123
    [skus] => Array
        (
            [0] => Array
                (
                    [is_shippable] => y
                    [actual_price] => 100.55
                    [selling_price] => 150.54
                    [quantity_type] => finite
                    [quantity_total] => 10
                    [bucket_value] => 
                    [sort_order] => 1
                )

        )

    [users_id] => 1
    [user_profiles_id] => 1

产品值必须转到产品表,并且必须将skus详细信息插入到skus表中,其中products_id位于skus表中。

如何在存储库模式中完成此操作。我关注的存储库模式是

L5 Repository pattern

1 个答案:

答案 0 :(得分:-1)

您的产品:

function skus()
{
    return $this->hasMany('App\Entities\Sku','skus_id');
}

你的Skus:

function product()
{
    return $this->belongsToMany('App\Entities\Product','products_id');
}

首先保存产品:

$product = new Product($request->all());
$product->save();

然后保存skus:

$product = Product::find($product->id);
$product->skus()->create($request->all());

您需要确保该字段为$fillable的所有此方法。