Reputation: 894
Ok, working in Laravel with eloquent so i have the concept of a ContentType
model and a Template
model. I have a form where you set data for the Content Type and you select from a drop down list of templates which one is to be associated with the content type. My models look like this:
ContentType:
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');
}
}
Template:
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');
}
}
What i want to do is store or update the template value. Is there a way of doing this straight off of . the ContentType
model instead of saving that relationship through the Template
model? Or should i adjust the types of relationship i have in the first place?
Upvotes: 1
Views: 448
Reputation: 9942
You could do it like this:
$contentType->template()->update([
'colToBeUpdated' => 'new value',
]);
This will execute 1 query to update the template
of the $contentType
.
But if you just want to change the template_id
(to associate $contentType
with some other template) you could just do:
$contentType->template()->associate($newId);
Or
$contentType->update(['template_id' => $newId]);
Upvotes: 1