【问题标题】:storing and updating has-many relationships laravel存储和更新有很多关系 laravel
【发布时间】:2017-11-21 13:32:21
【问题描述】:

关于使用 haMany Relations 存储数据 汽车可能不止图片 而且每张图片只能有一辆汽车

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

汽车图像模型

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


  }

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

有什么帮助吗?

【问题讨论】:

  • 可能问题与DB结构有关。你能展示你的迁移吗?或者尝试在关系声明中提供有效的 local_key - return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
  • class CreateForeignKeys extends Migration { public function up() { Schema::table('cars_images', function(Blueprint $table) { $table->foreign('car_id')->references('id')->on('cars') ->onDelete('cascade') ->onUpdate('cascade'); });
  • 当我尝试Car::find(1)->cars_images()->save($img);时一切正常
  • 我没有使用 DB:transaction 和 laravel。不使用事务是否有效?

标签: laravel has-many


【解决方案1】:

只需使用create 方法:

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

别忘了在你的模型中使用$fillable

【讨论】:

  • 早上好,当我使用 tinker 时,car_id 再次以 NULL protected $fillable = array('url','car_id'); 传递,一切正常!
  • public function store(Request $request) { $datas = $request->except('url'); $img_name = $request->get('url'); $car = Car::create($datas); $img = CarsImage::create(['url'=>$img_name, 'car_id'=> $car->id]); return 'saved ya si zebi saved'; } 这对我有用,但这里没有关系,就像使 Relation Manualy 一样
  • 创建方法不存储具有多个关系的多行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2017-05-12
  • 1970-01-01
  • 2014-07-10
  • 2015-08-05
  • 2016-10-12
  • 1970-01-01
相关资源
最近更新 更多