【问题标题】:Laravel orderBy Not Passing to ViewLaravel orderBy 不传递给视图
【发布时间】:2016-01-24 19:41:39
【问题描述】:

我正在使用以下代码从我的数据库表中提取一个集合。

$profileVisits = DB::table('recently_visited')
    ->where('visitor_id',Auth::user()->id)
    ->orderBy('times_visited', 'desc')->get();

    return view('profile.index')
        ->with([
            'user' => $user,
            'posts' => $posts,
            'profileVisits' => $profileVisits,
        ]);

当我 dd($profileVisits) 时,它会显示具有正确降序结果的集合。但是,当我使用以下代码将信息拉入我的视图时,它不会像预期的那样下降。 orderBy 查询构建器是否被撤消或带有“返回视图...”代码的东西?

查看代码...

@if (!$user->profileVisits->count())

@else
    @foreach ($user->profileVisits as $topVisits)
        <p>{{ $topVisits->getUsername() }}</p>
    @endforeach
@endif

用户模型:

public function profileVisits()
    {
        return $this->BelongsToMany('App\Models\User', 'recently_visited', 'visitor_id', 'profile_id');
    }

    public function addProfileVisits(User $user)
    {
        $this->profileVisits()->attach($user->id);
    }

    public function previouslyVisited(User $user)
    {
        return (bool) $this->profileVisits()->get()->where('id', $user->id)->count();
    }

【问题讨论】:

  • 你能发布你的模型及其关系

标签: laravel


【解决方案1】:

其实,我只是想通了。在用户模型上,我添加了 orderBy 而不是在控制器中使用它。见下文。

用户模型:

public function profileVisits()
{
    return $this->BelongsToMany('App\Models\User', 'recently_visited', 'visitor_id', 'profile_id')->orderBy('times_visited', 'desc');
}

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 2021-11-20
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2015-01-11
    相关资源
    最近更新 更多