LoginSignup
10
10

More than 5 years have passed since last update.

laravel4: SQLに常に固定条件を入れる

Last updated at Posted at 2013-09-02

公開サイトで 各テーブルのデータ公開条件を is_visible とかで制御してる場合があります。

select * from article where is_visible = 1

Laravelだと 以下。

$articles = Article::where('is_visible','=',1)->get();

結構条件入れ忘れて出しちゃったりするよねー。

たとえば 記事1レコードほしいとき 以下で取得したいけどー
$article = Article::find(1);

公開ステータスみないといけないので

$article = Article::where('is_visible','=',1)
->where('id','=',$id)
->first();

とかしないといけない

面倒ですよねー。ついでに公開日とかチェックしないといけない時もある。

ってことで newQueryをフックすればできます。
各テーブルごとに条件やcolumn名が違う場合があるので 条件は whereRaw で指定できるようにしてます。

ベースのクラス(model/DbHook.php)
abstract class DbBase extends Eloquent {
    protected static $onlyPubliced = false;    // 公開条件を有効にしてクエリを発行するか
    protected static $condPubliced = null;     

    public function newQuery($excludeDeleted = true)
    {
        $query = parent::newQuery($excludeDeleted);
        if( static::$onlyPubliced ){
            if ( static::$condPubliced ){
                $cond  = static::$condPubliced;
                $query = $query->whereRaw($cond[0], $cond[1]);
                return $query;
            }
            return $query;
        }
        return $query;
    }

    public static function allowAll()
    {
        static::$onlyPubliced = false;
        return new static;
    }
    public static function denyAll()
    {
        static::$onlyPubliced = true;
        return new static;
    }
}
model/Article.php
class Article extends DbHook{
    protected $table = 'article';
    protected $primaryKey = 'id';

    protected static $onlyPubliced = true;
    protected static $condPubliced = array('article.is_visible=? and start_at<=now() ', array(1));
}

こうすると $condPubliced に書いた条件が必ずSQLで実行され Article::find(1); とかしても SQLは select * from article where id=1 and article.is_visible=1 and start_at<=now() が実行されます。

公開条件をいろいろかかなくても モデルに書いとけばいいでーす。

全データを対象にしたい時は Article::allowAll(); と呼んでから 普通に Article::all() とかすればいいでーす。
戻したいときは Article::denyAll();すれば 固定クエリがまた読み込まれるようになります!

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10