将变量从组件传递到模型范围

时间:2017-02-20 06:20:28

标签: php laravel laravel-5 octobercms

我正在使用基于Laravel的OctoberCMS。

我正在尝试从URL获取标识符并将其传递给Scope以过滤数据库结果。

$ this-> property('username')可以运行并从URL返回用户名。

但是如何将它传递给模型并进入Scope函数?

以下是动态范围下的指南。

https://octobercms.com/docs/database/model#query-scopes

网页

网址:localhost / user / matt

标识符:/ user /:username

结果组件

public function init()
{
    // get username from url
    $username = $this->property('username'); //matt

    // pass username to scope
    Gallery::applyUser($username);
}

图库模型

// return results that match username
public function scopeApplyUser($query, $username)
{
    return $query->where('username', $username);
}

错误

Missing argument 2 for MyVendor\Gallery\Models\Gallery::scopeApplyUser()

解决方案吗

我发现添加($ query,$ username = null)允许变量无错误地传递。

但现在问题是$ username同时是'matt'和null,并且从未进入查询返回。

// return results that match username
public function scopeApplyUser($query, $username = null)
{
    print $username; //prints matt
    if ($username == null) { print 'null'; } //prints null

    return $query->where('username', $username); //returns null
}

diagram

1 个答案:

答案 0 :(得分:1)

在模型库中,您需要一个现场用户:

class Gallery extends Model {
    /** these are just placeholder variables you should be recognising these from your own model.!**/
    protected $table = 'gallery';
    protected $guarded = ['*'];
    protected $fillable = ['username'];// Make sure this also is in the database!!
    public scopeWhereUser($query, $user = null) {
        if(!is_null($user)) { // Only do something if the username is provided!
           $query->where('username',$user);
        }
    }
}

然后,当你有零检查时,你可以用

来调用它
 $gallery = new Gallery();
 $query = $gallery->newQuery()->where('x','y')->whereUser('matt');

我所做的改变:

  • 将范围重命名为whereuser而不是apply user,因为以这种方式命名它更合乎逻辑。适用于永久改变状态的功能
  • 添加了一个not is_null()检查,仅在查询不为空时限制查询。

打印结果的完整工作示例:

 $gallery = new Gallery();
 $query = $gallery->newQuery()->where('x','y')->whereUser('matt');
 $results = $query->get();
 foreach($results as $galleryItem) {
     echo $galleryItem->getKey() . ' is having:<BR/>';
     echo dump([
               'model'=>$galleryItem,
               'methods' => get_class_methods(get_class($galleryItem)),
               ]);
 }