我正在建立一个应用程序目前laravel管理相机和镜头。每个相机有一个镜头,反之亦然。
问题是,当我改变相机上的镜头在镜片表camera_id设置,旧的价值仍然是旁边的老镜头。
Example:Lens 1 belongs to Camera 1 - camera_id on Lens 1 = 1, camera_id on Lens 2 = 0Lens 1 is changed to belong to Camera 2 - camera_id on both Lens 1 & 2 is now 1
我尝试了很多方法让它改变camera_id镜头1为零,因为,否则,当它去抢,相机镜头,它抓住了很多的第一次,这是错误的。
我已经搜索不成功的一个小时,发现信息associate(),这显然改变了一对一的关系:它仍然做同样的事情。
功能使变化:
function changeLensOnCamera() {
$camera = Camera::find($_POST['camera_id']);
$lens = Lens::find($_POST['lens_select']);
$lens->camera()->associate($camera);
$lens->save();
return Redirect::to('cameras');
}
模型
class Lens extends Eloquent
{
use SoftDeletingTrait;
protected $table = 'lens';
protected $dates = ['deleted_at'];
protected $fillable = array('camera_id');
public function camera()
{
return $this->belongsTo('Camera');
}
public function manufacturer()
{
return $this->belongsTo('LensManufacturer');
}
}
?>
<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Camera extends Eloquent
{
use SoftDeletingTrait;
protected $table = 'cameras';
protected $dates = ['deleted_at'];
protected $fillable = array('lens_id');
public function lens()
{
return $this->hasOne('Lens');
}
}
?>
我已经试过了:
Lens::find($_POST['lens_select'])->camera->update(array('camera_id' => 0));
很好,但似乎没有真正使数据库中的变化。有我丢失的东西吗?
感谢