繁体   English   中英

Laravel中是否有一种简单的方法来更新一对一的关系,并具有更新旧的和新的关系?

[英]Is there an easy way within Laravel to update a one-to-one relationship and have it update the old as well as the new?

我目前正在构建一个Laravel应用来管理相机和镜头。 每个摄像机可以有一个镜头,反之亦然。 问题是,当我通过在镜头表中设置camera_id来更换镜头的镜头时,旧值保留在旧镜头旁边。 示例:镜头1属于相机1-镜头1上的camera_id = 1,镜头2上的camera_id = 0镜头1更改为属于相机2-镜头1和2上的camera_id现在都为1我尝试了多种制作方法它将镜头1的camera_id更改为零,这是因为,否则,当它要抓住该镜头的镜头时,它会抓住第一个镜头,这是错误的。 我已经搜索了一个小时左右,但未成功,但是发现了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));

同样,但是它似乎并没有真正在数据库中进行更改。 有什么我想念的吗? 谢谢

使用它来清除与相机关联的镜头:

$camera->lens()->update(array('camera_id' => 0));

我认为摆放桌子的方式实际上在相机和镜头上有一对多的关系。 从技术上讲,如果camera_id指向多个镜头行上的同一台摄像机,则可以有多个镜头属于一个摄像机。

您可能应该做的是改为将lens_id列添加到camera表中,并通过该列将camera与镜头相关联。 这样,只能有一个与特定相机相关的镜头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM