我正在laravel中创建一个API,以获取其创建者的所有帖子。
我有下表-
帖子
id
标题
desc
creator_id->属于用户ID
creator_name
类型-ENUM('system','user')“当'system'时,将给出creator_name,否则将使用creator_id从用户表中获取名称”
用户
id
名称
。
。
在laravel中,我们具有发布和用户模型。 系统帖子由admin创建,并提供了creator_name。对于系统帖子,我们希望显示帖子表中creator_name字段中的创建者名称,而不是管理员用户的详细信息。
在laravel中实现此目标的最佳方法是什么?
Post Model -
class Post{
function creator(){
return $this->belongsTo('App\Models\User', 'creator_id');
}
}
Post Controller -
public function index()
{
$posts = Post::with('creator')->paginate();
$data = $posts->toArray();
foreach ($data['data'] as $key => &$value) {
if($value['type'] === 'system' && isset($value['creator'])){
$value['creator']['name'] = $value['creator_name'];
unset($value['type']);
unset($value['creator_name']);
}
}
return $this->sendResponse($data);
}
expected:
Posts -
[
{
"id": 1,
"title": "some title",
"desc": "some description",
"creator_name": NULL,
"creator_id": 123,
"creator": {
"id": 123,
"name": "John Doe",
},
"type": "user"
},
{
"id": 2,
"title": "some other title",
"desc": "some other description",
"creator_name": "Jane Doe",
"creator_id": 12, // admin user
"creator": {
"name": "Jane Doe", // creator_name rather than details of admin user
},
"type": "system"
}
]