Laravel范围不起作用

时间:2017-02-18 20:57:07

标签: laravel

迁移class CreatePostsTable extends Migration

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->text('number')->nullable();
        $table->text('text');
        $table->boolean('is_approved')->default(0);
        $table->timestamp('published_at');
        $table->timestamps();
        $table->softDeletes();
    });
}

模型Post

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'text',
        'number'
    ];

    protected $dates = ['published_at', 'deleted_at'];

    public function setPublishedAtAttribute($date) 
    {
        $this->attributes['published_at'] = Carbon::now('Europe/Moscow');
    }

    public function scopeApproved($query) 
    {
        $query->where('is_approved', '==', '1');
    }
}

Controller HomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Post;

class HomeController extends Controller
{
    public function index() {
        $posts = Post::latest('published_at')->approved()->paginate(20);
        return view('home.index', compact('posts'));
    }
}

因此,预计在主页上我只会收到approved个帖子,而是会在页面上显示所有帖子。怎么了?

1 个答案:

答案 0 :(得分:2)

你的范围使用wc运算符,这对于php非常有用,但由于运算符将在查询中使用,因此只需要一个常规的等号:

==

或者只是

$query->where('is_approved', '=', '1');