【问题标题】:Getting user related buildings using whereHas in User model eloquent在用户模型 eloquent 中使用 whereHas 获取用户相关的建筑物
【发布时间】:2017-10-22 04:05:54
【问题描述】:

我在 App\User Model 文件中有以下方法

Public function buildings(){
        return Building::whereHas('area', function ($q) {
            $q->whereHas('users', function ($q) {
                $q->where('users.id', auth()->id());
            });
        })->get();
    }

当我尝试在视图文件中获取用户建筑物时,我收到了这个错误:

@foreach (Auth::user()->buildings as $b)
    {{$b->name}}
                @endforeach

App\User::buildings 必须返回一个关系实例。 (查看:C:\xampp\htdocs\hse\resources\views\observations\form_observation.blade.php)

我尝试了web.php中的代码,它可以工作,这意味着关系设置是完美的,但我希望它可以在用户模型中工作

Route::get('/', function () {
    return App\Building::whereHas('area', function ($q) {
$q->whereHas('users', function ($q){
    $q->where('users.id',11);
});
    })->get();
});

【问题讨论】:

标签: php mysql sql laravel eloquent


【解决方案1】:

在您的视图文件中,您应该调用 building() 函数以返回一个 Relation 实例(即返回一个关系对象)

改变

@foreach (Auth::user()->buildings as $b)
    {{$b->name}}
                @endforeach

@foreach (Auth::user()->buildings() as $b)
    {{$b->name}}
                @endforeach

【讨论】:

    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 2012-10-22
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多