存储和更新有许多关系laravel

时间:2017-11-20 20:12:49

标签: laravel has-many

关于使用haMany Relatiions存储数据 汽车可能不仅仅是画面 每张照片只能有一辆车

汽车调制解调器Car.php

class Car extends Model 

{

protected $table = 'cars';
public $timestamps = true;

use SoftDeletes;

protected $dates = ['deleted_at'];
protected $fillable = array('Marque', 'Model', 'sieges', 'climatisation', 'portes', 'transmition', 'price','url','car_id');

public function cars_images()
{
    return $this->hasMany(CarsImage::class);
}

CarsImage模型

class CarsImage extends Model 

{

protected $table = 'cars_images';
public $timestamps = true;

use SoftDeletes;

protected $dates = ['deleted_at'];
protected $fillable = array('url');

public function cars()
{
    return $this->belongsTo(Car::class);
}

}

MyController:

public function store(Request $request)   {

      $car = new Car;
      $car->Marque = Input::get('Marque');
      $car->Model = Input::get('Model');
      $car->sieges = Input::get('sieges');
      $car->climatisation = Input::get('climatisation');
      $car->portes = Input::get('portes');
      $car->transmition = Input::get('transmition');
      $car->price = Input::get('price');

      $img = new CarsImage;
      $img->url = 'jean Luc Picard';

      DB::transaction(function() use ($car, $img) {
          $car = $car->save();
          Car::find($car->id)->cars_images()->save($img);
      });
      return 'ok';


  }

问题是汽车已保存并且网址也已保存但没有car_id

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

只需使用create方法:

$car = Car::create([
          'Marque' => $request->Marque,
          //other fields...
       ]);
$image = $car->cars_images()->create([
           'url' => 'jean Luc Picard'
       ]);

并且不要忘记在模型中使用$fillable