簡體   English   中英

從條件為laravel 5.7的模型獲取數據

[英]get data from model with condition laravel 5.7

我的Laravel項目中有Users_group模型。

碼:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class Users_group extends Model
{
    use Notifiable;

    protected $table = 'users_groups';
    protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];

    public function getGroupData()
    {
        return $this->hasOne('App\Group','id','group_id');
    }
}

當我想從該模型中獲取數據時,請使用以下自定義方法:

$data = App\Users_group ::get();

很好用

我想從條件不是這樣的模型中獲取數據:

$data = App\Users_group::where('group_id','>',5)->get();

我需要將條件放入模型文件中,這使得每次我調用User_group::get()時都會在模型內部返回條件時使模型返回數據。

謝謝!

您可以使用查詢范圍來實現此目的。 查詢范圍使您可以向模型添加全局約束。

您可以在模型中添加以下啟動方法:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('groupOver5', function (Builder $builder) {
        $builder->where('group_id', '>', 5);
    });
}

通過在模型中使用scope來嘗試這一點

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class Users_group extends Model
{
    use Notifiable;

    protected $table = 'users_groups';
    protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];



     public function scopeGetGroupData($query,$value,$opertor = '>')
        {
            return $query->where('group_id', $opertor, $value);
        }

}

像這樣在控制器中獲取數據,您還可以在方法中傳遞參數

App\Users_group::GetGroupData($value)->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM