使用with()和find()同时使用find限制列会取消关系数据

时间:2017-01-06 21:14:39

标签: laravel eloquent laravel-eloquent

我有以下代码显示不同的数据,具体取决于您是否是经过身份验证的用户查看您自己的数据,或者您是否正在查看来自其他用户的数据。代码有效,但在我看来非常讨厌。

public function showUserDetailed(Request $request, $username)
    {
    $key = strtolower($username).'-data-detailed';

    if(Auth::user()->usenrame === $username) {
        $key = $key .'-own';
    }

    if(Cache::has($key)) {
        if($request->wantsJson()) {
            return request()->json(Cache::get($key));
        } else {
            return view('user/detailed', ['user' => Cache::get($key)]);
        }
    } else {
        if(Auth::user()->username === $username) {
            $u = User::where('username', $username)->first();

            $user = new \stdClass();
            $user->username = $u->username;
            $user->email = $u->email;
            $user->address = $u->address;
            $user->city = $u->city;
            $user->state = $u->state;
            $user->zip = $u->zip;
            $user->phone = $u->phone;
            $user->follows = $u->follows;
            $user->ratings = $u->ratings;
            $user->location = $u->location;
        } else {
            $u = User::where('username', $username)->first(['username', 'city', 'state']);

            $user = new \stdClass();
            $user->username = $u->username;
            $user->city = $u->city;
            $user->state = $u->state;
            $user->follows = $u->follows;
            $user->ratings = $u->ratings;
        }

        Cache::put($key, $user);

        if($request->wantsJson()) {
            return response()->json($user);
        } else {
            return view('user/detailed', ['user' => $user]);
        }
    }
}

我试图在模型调用中使用类似于以下的东西。

User::where('username', $username)->with('follows', 'ratings', 'location')->find(['username', 'city', 'state');

但是,当我指定要从用户表中获取的列时,它会取消关系数据,因此它将作为空数组返回。有没有不同的方法可以做到更清洁?我鄙视在这种情况下必须创建一个stdClass作为数据容器,并且觉得我可能会遗漏一些东西。

// this works
User::where('username', $username)->with('follows', 'ratings', 'location')->first();

// this also works
User::where('username', $username)->first(['username', 'city', 'state']);

// this does not
User::where('username', $username)->with('follows', 'ratings', 'location')->first(['username', 'city', 'state']);

1 个答案:

答案 0 :(得分:1)

当您指定列并希望获取相关模型时,您需要在所选列中包含id(或您正在使用的任何外键)。

关系执行另一个查询,如下所示:

SELECT 'stuff' FROM 'table' WHERE 'foreign_key' = ($parentsId)

所以它需要知道父(原始模型)的id。相同的逻辑适用于不同形式的所有关系。