【发布时间】: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表上执行查询。所以,如果我理解正确,你只是想知道如何通过关系来做到这一点(这可能是更好的方式)?