【发布时间】: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。不使用事务是否有效?