首页 文章

Laravel和Eloquent在hasOne方面保存关系

提问于
浏览
1

好的,在雄辩的Laravel工作,所以我有 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 模型保存该关系?或者我应该首先调整我的关系类型?

1 回答

  • 1

    你可以这样做:

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

    这将执行1次查询以更新 $contentTypetemplate .

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

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

    要么

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

相关问题