2017-03-27 9 views
0

1対多関係で複数のレコードを保存しようとしています。私は次の2つのモデルを持っています。複数のレコードを1対多の関係で保存するlaravel 5

Product Model

class Product extends Model 
{ 
    protected $primaryKey = 'product_id'; 
    public $timestamps = FALSE; 

    public function Size(){ 
     return $this->hasMany('App\Size'); 
    } 

} 

Size Model

class Size extends Model 
{ 
    public $timestamps = FALSE; 
    protected $fillable = ['product_id','size']; 

    public function Product(){ 
     return $this->belongsTo('App\Product'); 
    } 
} 

私は、製品の大きさを保存したいです。 私のコントローラは

public function store(Request $request){ 

     $product_id = Products::select('product_id')->orderBy('product_id','desc')->first(); 

     if($request->size_m) $sizes[] = array("size" => $request->size_m); 
     if($request->size_l) $sizes[] = array("size" => $request->size_l); 
     if($request->size_s) $sizes[] = array("size" => $request->size_s); 

     $product_id->Size()->saveMany($sizes); 


    } 

あるしかし、私は、問題は何

FatalThrowableError in HasOneOrMany.php line 221: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in D:\e-commerec\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 237

次のエラーを取得していますか?

答えて

1

[OK]を、のは、https://laravel.com/docs/5.4/eloquent-relationshipsから例から始めてみましょう:

$post = App\Post::find(1); 

$post->comments()->saveMany([ 
    new App\Comment(['message' => 'A new comment.']), 
    new App\Comment(['message' => 'Another comment.']), 
]); 

問題

あなたは配列の配列を渡します。それは間違っている。

$product_id->Size()->saveMany([ 
    new App\Size(['size' => 1])  
]); 
+1

ありがとう:あなたはサイズの配列を渡す必要があり

ソリューション

はそうのように簡略化され、オブジェクト。助けて –

+0

私はまた、このモデルを考慮する関係を更新することに問題があると私はそれを更新する必要があります。多対多のリレーションのsync()メソッドとは異なり、1対多リレーションシップを更新するには3つの方法がありますが、それを行う別の方法かもしれません。私を助けることができますか?メソッド呼び出しはassociate()です。しかし、私はそれがドキュメントからどのように動作するのか理解していませんでした –

+0

あなたは一意の関係を保存したいだけですか? – schellingerht