简体   繁体   English

Laravel 5:如何使用'where'或'orderBy'使用雄辩?

[英]Laravel 5: How to use 'where' or 'orderBy' using eloquent?

First things first, this is not a duplicate of Laravel 4: how to "order by" using Eloquent ORM 首先,这不是Laravel 4的重复:如何使用Eloquent ORM“排序”

I have this model User, then I have this other model Idea. 我有这个模型用户,然后我有这个其他模型的想法。 I'm writting a view with the details of the user, and I want to post all the ideas the user has suggested. 我正在编写一个包含用户详细信息的视图,我想发布用户建议的所有想法。 Now, the ideas have a status, the first status is "DRAFT", that means only the user who posted the idea can review it, the idea should not be shown to other users looking at the profile. 现在,这些想法都有一个状态,第一个状态是“DRAFT”,这意味着只有发布该想法的用户才能查看它,这个想法不应该显示给查看该配置文件的其他用户。

Using eloquent I could do something like: 使用雄辩,我可以做类似的事情:

@foreach($user->idea as $idea)
    ...display details...
@endforeach

My problem is that this approach would cycle through all ideas AND in the order where they were introduced. 我的问题是,这种方法会循环所有的想法,并按照它们的介绍顺序循环。 I can add an @if to show only what I want, like 我可以添加一个@if来显示我想要的东西,比如

@foreach($user->idea as $idea)
    @if($idea->status !='DRAFT')
        ...show the idea...
    @endif
@endforeach

But I don't think it's the smart way to do it, I'd like to do something like 但我不认为这是明智的做法,我想做点什么

$ideas = $user->idea->where('status', '<>', 'DRAFT')

and then cycle through the $ideas variable, or at least, I'd like somtehing like 然后循环通过$ideas变量,或者至少,我喜欢像somtehing一样

$ideas = $user->idea->orderBy('created_at', 'desc')

But I have no idea on how to do it. 但我不知道该怎么做。

You can do it like this: 你可以这样做:

$ideas = $user->idea()
    ->where('status', '<>', 'DRAFT')
    ->orderBy('created_at', 'desc')
    ->get();

When you use ->idea() it will start a query. 当你使用->idea() ,它将启动一个查询。

For more information about how to query a relationship: https://laravel.com/docs/5.7/eloquent-relationships#querying-relations 有关如何查询关系的更多信息: https//laravel.com/docs/5.7/eloquent-relationships#querying-relations

You can user where clause like this 您可以使用where where子句

DB::table('products_to_categories')
    ->where('categories_id', $id )
    ->update([
        'categories_id' => $unassigned_cat_id
    ]);

and you can use orderBy clause like this 你可以像这样使用orderBy子句

DB::table('products_to_categories')
    ->where('categories_id', $id )
    ->orderBy('subId','DESC');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM