我有两个模型1.主题2.条件。在这之间我有 1对1关系 。现在,我有一个外键subject_id和d在 json < / strong>格式。现在我想获取以json格式subject_id存储的ID的主题名称 Subject.php
class Subject extends Model
{
protected $fillable=['name','department_id'];
public function condition()
{
return $this->hasOne(Condition::class);
}
}
Condition.php
class Condition extends Model
{
protected $fillable=['subject_id','department_id','total'];
protected $casts=['subject_id' => 'array']
public function subject()
{
return $this->belongsTo(Subject::class);
}
}
在这里,我试图从 json id's
中获取所有主题名称。$condition=Condition::find(4);
foreach ($condition->subject_id as $key => $subject) {
$list[]=$subject->subject->name;
}
dd($list);
我想知道是否可以从json id中检索主题的名称,如果可以,请帮助我获取它。
答案 0 :(得分:0)
<罢工> 尝试这个:
foreach ($condition->subject->subject_id as $key => $subject) {
$list[]=$subject->subject->name;
}
答案 1 :(得分:0)
嘿,我有个想法,可以像下面这样使用
$condition=Condition::find(4);
$subjects=Subject::whereIn('id',$condition->subject_id)->get();
dd($subjects);
如果有人有更好的方法来获得此结果,请告诉我们