我有一个表,其中的json列转换为数组。
在我的课上:
protected $casts = [
'row_ids' => 'array',
];
Run Code Online (Sandbox Code Playgroud)
我通过另一个类中的关系访问此列:
public function table_rows()
{
return $this->hasMany(TableChannelRow::class, 'channel_api_id', 'api_id');
}
Run Code Online (Sandbox Code Playgroud)
当dd建立关系时,我可以看到目标表中的列正常,其中一列包含预期的数组:
dd($channel->table_rows);
#attributes: array:4 [?
"api_id" => 2
"table_api_id" => 1
"channel_api_id" => 6
"row_ids" => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, ?"
]
Run Code Online (Sandbox Code Playgroud)
在我的Blade模板页面中,检查当前记录id是否在列数组中,如下所示:
@foreach($channels as $channel)
@if(in_array($row->api_id, $channel->table_rows->row_ids)) true @endif
@endif
Run Code Online (Sandbox Code Playgroud)
但这失败了:
Property [row_ids] does not exist on this collection instance.
Run Code Online (Sandbox Code Playgroud)
我错过了什么?谢谢。
您的table_rows关系返回一个集合。因此,您必须遍历集合或获取集合中的第一个实例:
$channel->table_rows->first()->row_ids
Run Code Online (Sandbox Code Playgroud)