存储和更新 has-many 关系 laravel

storing and updating has-many relationships laravel

我想用 haMany 关系存储数据 汽车可能不止图片 而且每张图片只能有一辆汽车

车载调制解调器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);
}

}

我的控制器:

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';


  }

问题是汽车得救了,url 也得救了,但 car_id

没有

有什么帮助吗?

只需使用create方法:

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

别忘了在模型中使用 $fillable