我有模型“帖子”,其中包含“id”、“名称”、“内容”和“状态”列
我有模型“PostStatus”,其中包含“id”和“name”列
在 Post.php 我有以下内容:
class Post extends Model
{
public function status()
{
return $this->belongsTo('App\PostStatus','status');
}
}
在其他地方的控制器中,我有:
Post::with('status')->get()->toArray();
它返回一个数组,其中所有帖子的“id”、“名称”作为“内容”作为它们的列值,“状态”作为帖子状态表中相关行的数据数组。我想要实现的是“状态”列只是 PostStatus 模型中“名称”列的字符串值,而不是整行的数组。我尝试在 Post 模型中的 status 函数上使用 ->select ,但这仍然将值作为数组返回。我宁愿避免直接使用 SQL 来实现我的目标。
总之,我希望控制器中的函数返回:
array(4) {
["id"]=>
int(1)
["name"]=>
string(12) "Post Example"
["content"]=>
string(7) "Content"
["status"]=>
string(6) "Active"
}
而不是
array(4) {
["id"]=>
int(1)
["name"]=>
string(12) "Post Example"
["content"]=>
string(7) "Content"
["status"]=>
array(2) {
["id"]=>
int(1)
["name"]=>
string(6) "Active"
}
}