场景:取出一篇文章对应的所有tags,已经关联好了多对多模型
`class Article extends Model
{
public $timestamps=false;
protected $table='article';
protected $primaryKey='art_id';
protected $guarded=['art_id'];
protected $events=[
'created'=>ArticlePublished::class,
];
public function tags() {
return $this->belongsToMany(Tag::class,'article_tag','tag_id','article_id');
}
}`
然后在控制器中
`$art=Article::find($art_id);
//tags
$tags=$art->tags()->select('id','text')->get();
dd($art->tags);`
结果只取到了1个tag
`Collection {#572 ▼
#items: array:1 [▼
0 => Tag {#573 ▼
#guarded: array:1 [▶]
#primaryKey: "id"
#table: "tags"
#connection: "mysql"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▶]
#original: array:8 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:1 [▶]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
]
}`
昨天试了好久都只能取到一个啊。。问了好多人也不能解决这个奇怪的问题