【问题标题】:Laravel and Eloquent saving relationship on the hasOne sideLaravel 和 Eloquent 在 hasOne 端的保存关系
【发布时间】:2018-03-09 21:09:30
【问题描述】:

好的,在 Laravel 中以 eloquent 工作,所以我有 ContentType 模型和 Template 模型的概念。我有一个表单,您可以在其中设置内容类型的数据,然后从模板的下拉列表中选择要与内容类型关联的模板。我的模型如下所示:

内容类型:

namespace App;

use Illuminate\Database\Eloquent\Model;
use \Hyn\Tenancy\Traits\UsesTenantConnection;

class ContentType extends Model
{
    use UsesTenantConnection;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'parent_content_id', 'name', 'description', 'is_requestable', 'status',
    ];

    /**
     * Get the template that owns the content type.
     */
    public function template()
    {
        return $this->belongsTo('App\Template');
    }

    /**
     * Get the entity groups for the content type.
     */
    public function entity_groups()
    {
        return $this->hasMany('App\EntityGroup');
    }

    /**
     * Get the entities for the content type.
     */
    public function entities()
    {
        return $this->hasMany('App\Entity');
    }
}

模板:

namespace App;

use Illuminate\Database\Eloquent\Model;
use \Hyn\Tenancy\Traits\UsesTenantConnection;

class Template extends Model
{
    use UsesTenantConnection;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'filename', 'status',
    ];

    /**
     * Get the content types for the template.
     */
    public function content_types()
    {
        return $this->hasMany('App\ContentType');
    }
}

我想要做的是存储或更新模板值。有没有办法直接做到这一点。 ContentType 模型而不是通过 Template 模型保存该关系?还是我应该首先调整我的关系类型?

【问题讨论】:

  • 你能解释更多你想要什么吗?你说你想更新模板?是不是很像$template->update([])?。
  • @ako,我想更新内容类型和模板的关系。本质上,我在template_id 的内容表上有一个专栏,这就是我要更新的数据。我正在更新其他 . content_type 的属性所以我想看看我是否可以在不查找并进行 SQL 调用来获取模板的情况下做到这一点。我可以只更新内容类型记录吗?我是 Laravel 和 Eloquent 的新手,所以也许我以错误的方式构建了这个问题。如果我不需要的话,我只想不必实例化模板对象。
  • 有更好的方法,是的。但在幕后,它仍然会在templates 表上执行查询。所以,如果我理解正确,你只是想知道如何通过关系来做到这一点(这可能是更好的方式)?

标签: php laravel eloquent


【解决方案1】:

你可以这样做:

$contentType->template()->update([
    'colToBeUpdated' => 'new value',
]);

这将执行 1 个查询来更新 template$contentType

但是,如果您只想更改 template_id(将 $contentType 与其他模板关联),您可以这样做:

$contentType->template()->associate($newId);

或者

$contentType->update(['template_id' => $newId]);

【讨论】:

  • 我想我的问题是,如果基本上我所做的只是更改content_types 表上的template_id 列,为什么还要触及template?另外,如果我需要更改我的关系,以便我可以更新content_types 表记录上的template_id 列,我可以这样做。
  • 不需要动。我的理解是你想更新相关模板上的一些不相关的列。你总是可以只做$contentType->template_id = $newValue 并保持templates 表不变。
  • @ryanpitts1 在那里,我更新了答案以反映这一点。让我知道这是否是您想要的。
  • @devk 请注意,associate() 实际上并没有保存记录,因此您仍然必须在 associate() 之后调用 $contentType->save()(或者,只需将 ->save() 附加到调用链上,因为associate() 无论如何都会返回 $contentType 值)。
猜你喜欢
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-04
  • 2019-11-19
  • 1970-01-01
  • 2020-06-02
  • 2017-12-13
  • 2020-10-06
相关资源
最近更新 更多