laravel - Applying global scope with join replaces main table column data with joined table column data having same column name in Laravel 8
问题描述
I'm using a made up scenario, but facing similar issue.
I'm using Laravel 8 and have two models Family & Centre
. Both containing common column name id
.
In model Family
I want to restrict families data based on centre of user logged in. For now I'm hardcoding it a dummy centre_id
Below is my booted
function in Family
model
protected static function booted()
{
static::addGlobalScope('user_access', function (Builder $builder) {
$builder->join('centres as c1', function ($join) {
$join->on('families.centre_id', '=', 'c1.id');
});
});
}
Now when I query Family
model in a controller, it joins with Centre
model and the id
column of Family
gets replaced with Centre
model id
column.
For eg:
Family has one row with id -> 100 and centre_id = 1 Centre has one row with id -> 1 and name = 'Test'
After join in booted function, I get value 1 in id
when I query $family->id
. $family
is an instance of Family
model.
Expected result : 100
I don't want to use select in booted function as there are many aggregated function I'm using which will be causing issues.
解决方案
推荐阅读
- powerbi - 何时在 Power BI 中使用计算字段与度量?
- javascript - 修复了导航栏在不在顶部且不滚动时消失的问题,无法按预期工作
- docker - 如何在 Docker 中通过端点创建不同的端口映射?
- python - 使用 python 请求发布带有数组的请求
- linux - 使用 io_uring 进行多路复用
- python - 如何将 WTForms 输入的默认时区更改为 MST
- python - Odoo-14:ValueError:ir.actions.report.report_type 的值错误:'qweb-pdf'
- reactjs - 使用 Laravel 护照 Oauth2 反应 js Web 应用程序
- c# - 通过正则表达式在c#中打开html标签
- powerbi - 在查询编辑中执行的编辑与在建模期间执行的编辑有什么区别?