首页 文章

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

提问于
浏览
2

我正在使用基于Laravel的OctoberCMS .

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

$ this-> property('username')工作并返回URL中的用户名 .

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

这是动态范围下的指南 .

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

Page

URL:localhost / user / matt

标识符:/ user /:username

Results Component

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

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

Gallery Model

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

Error

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

Solution?

我发现添加($ 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 回答

  • 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);
            }
        }
    }
    

    然后,当你有nullchecks时,你可以调用它

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

    我做的改变:

    • 将范围重命名为whereuser而不是apply user,因为以这种方式命名它更合乎逻辑 . 适用于永久改变状态的功能

    • 添加了一个not is_null()检查,仅在查询不为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)),
                   ]);
     }
    

相关问题