空合并运算符无法在 laravel eloquent 中工作
控制器
Tag::with('tagTranslation')->find(5)
标签模型
function tagTranslation()
{
$locale = Session::get('locale'); // $locale = 'bn';
return $this->hasOne(TagTranslation::class, 'tag_id')
->where('locale', $locale)
->select('tag_name', 'locale')
?? // Or ternary ?:
$this->hasOne(TagTranslation::class, 'tag_id')
->where('locale', 'en')
->select('tag_name', 'locale');
}
如果locale='bn'
,那么它会显示预期结果,例如:
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": {
"tag_id": 5,
"tag_name": "ডেস্কটপ",
"local": "en"
}
}
如果我设置数据库中不存在的locale='xyz'
,然后我想像这样显示locale='en'
上的默认数据库:
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": {
"tag_id": 5,
"tag_name": "Desktop",
"local": "en"
}
}
但它返回 NULL
值,如下
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": null
}
所示我可以解决吗?
Controller
Tag::with('tagTranslation')->find(5)
Tag Model
function tagTranslation()
{
$locale = Session::get('locale'); // $locale = 'bn';
return $this->hasOne(TagTranslation::class, 'tag_id')
->where('locale', $locale)
->select('tag_name', 'locale')
?? // Or ternary ?:
$this->hasOne(TagTranslation::class, 'tag_id')
->where('locale', 'en')
->select('tag_name', 'locale');
}
If locale='bn'
, then it is showing the expected results like:
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": {
"tag_id": 5,
"tag_name": "ডেস্কটপ",
"local": "en"
}
}
And if I set locale='xyz'
which does not exists in database, then I want to show default data base on locale='en'
like this:
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": {
"tag_id": 5,
"tag_name": "Desktop",
"local": "en"
}
}
But it returns NULL
value like this
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": null
}
How can I solve it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

你可以做类似的事情(它会检查 $locale 如果它不退出它返回'en'):
You can do something like that (It will check $locale if it does not exits it return 'en'):