Jon*_*ops 9 php laravel eloquent
我有两个具有多对多关系的模型.我希望能够使用一组id设置一个特定的属性,并在mutator中建立关系,如下所示:
<?php
class Profile extends Eloquent {
protected $fillable = [ 'name', 'photo', 'tags' ];
protected $appends = [ 'tags' ];
public function getTagsAttribute()
{
$tag_ids = [];
$tags = $this->tags()->get([ 'tag_id' ]);
foreach ($tags as $tag) {
$tag_ids[] = $tag->tag_id;
}
return $tag_ids;
}
public function setTagsAttribute($tag_ids)
{
foreach ($tag_ids as $tag_id) {
$this->tags()->attach($tag_id);
}
}
public function tags()
{
return $this->belongsToMany('Tag');
}
}
<?php
class Tag extends Eloquent {
protected $fillable = [ 'title' ];
protected $appends = [ 'profiles' ];
public function getProfilesAttribute()
{
$profile_ids = [];
$profiles = $this->profiles()->get([ 'profile_id' ]);
foreach ($profiles as $profile) {
$profile_ids[] = $profile->profile_id;
}
return $profile_ids;
}
public function profiles()
{
return $this->belongsToMany('Profile');
}
}
Run Code Online (Sandbox Code Playgroud)
但是该setTagsAttribute功能未按预期工作.我收到以下错误:SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert intoprofile_tag (profile_id ,tag_id) values (?, ?)) (Bindings: array ( 0 => NULL, 1 => 1, ))
And*_*eas 20
在保存模型之前,不能附加多对多关系.save()在设置之前调用模型$model->tags,你应该没问题.原因是模型需要具有Laravel可以放入数据透视表的ID,这需要两个模型的ID.
| 归档时间: |
|
| 查看次数: |
7455 次 |
| 最近记录: |