Laravel denies local reach

I am using laravel 5.2 for my project. I just implemented a local scope (let's use the laravel docs example for simplicity - https://laravel.com/docs/master/eloquent#local-scopes )

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Scope a query to only include popular users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

}

I'm calling:

$users = App\User::popular()->get();

And it works like a charm

Is it possible to cause negation of the scope?

$users = App\User::Notpopular()->get();

Or do I need to manually negate the specified area? If is the best way to do this?

Thank you in advance!

+4
source share
3 answers

( , ), , , . , .

:

public function scopeNotPopular($query) {
  $query->whereNotIn($this->getKeyName(), function($q) {
    $q->select($this->getKeyName())->from($this->getTable());
    $this->scopePopular($q);
  });
}

whereNotIn . . , .

, , , SQL-, , . , .

+3

"" .

public function scopePublished($query, $negate = false) {
    return ($negate ? $query->where('published', false) : $query->where('published', true));
}

, , $post->published()... , $post->published(true)...


, :

public function scopePublished($query, $override = true) {
    return $query->where('published', $override);
}

: $post->published()...
: $post->published(false)...

+2

I think you need to implement it manually, because Laravel will not automatically “deny”.

What you can do is use dynamic query areas: https://laravel.com/docs/5.0/eloquent#query-scopes

So, in the field of dynamic queries, you can pass additional parameters, and one of them can be, if it should be the most popular or less popular.

+1
source

Source: https://habr.com/ru/post/1623171/


All Articles