从控制器到模型获取var

时间:2018-01-24 12:02:17

标签: laravel eloquent

我在控制器中有一个变量($id),我想把它传递给模型:

控制器:

public function user_load_more($id, $friendly_url)
{
    $user = User::where('friendly_url', '=', $friendly_url)
        ->with('shares_load_more.links.tag', 'userProfile.get_following')
        ->with(['shares_load_more.links.page' => function ($query) {
            $query->select('id', 'name', 'friendly_url');
        }])->orderBy('id', 'desc')->first();

    return view("site.list.user.links", compact("user"));
}

MODEL(User.php):(?)

public function shares_load_more($id) //--- put the id here?
{
    return $this->hasMany(Share::class, 'user_id', 'id')
        ->select('id', 'link_id', 'user_id', 'shared_in', 'content', 'created_at')
        ->take(2)
        ->orderBy('id', 'desc')
        ->where('id', '<', $id)
        ->where('type', '=', 0);
}

1 个答案:

答案 0 :(得分:0)

你真的不需要在模型中传递变量,还有另一种方法可以做到这一点。

public function user_load_more($id, $friendly_url)
{
$user = User::where('friendly_url', '=', $friendly_url)
    ->with('shares_load_more.links.tag', 'userProfile.get_following')
    ->with(['shares_load_more' => function($query) use($id) {
    $query->where('id', '<', $id);
}, 'shares_load_more.links.page' => function ($query) {
        $query->select('id', 'name', 'friendly_url');
    }])->orderBy('id', 'desc')->first();

return view("site.list.user.links", compact("user"));
}

型号:

public function shares_load_more($id) //--- put the id here?
{
return $this->hasMany(Share::class, 'user_id', 'id')
    ->select('id', 'link_id', 'user_id', 'shared_in', 'content', 'created_at')
    ->take(2)
    ->orderBy('id', 'desc')
    ->where('type', '=', 0);
}

它将附加到关系查询

相关问题