2017-02-20 14 views
2

我使用的是基於Laravel的OctoberCMS。從組件向模型範圍傳遞變量

我想從URL獲取標識符,並將其傳遞給Scope來過濾數據庫結果。

$ this-> property('username')起作用並從URL返回用戶名。

但是,你如何將它傳遞給模型和範圍函數?

以下是Dynamic Sc​​opes下的指南。

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

URL:本地主機/用戶/無光澤

標識符:/用戶/:用戶名

結果組件

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() 

解決方案?

我發現添加($查詢,$ 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

+0

嘗試使用如下$的用戶名,以獲得從url屬性= $ _GET [ '用戶名'];而不是$ username = $ this-> property('username');你會知道真正的財產可以被訪問。 –

+0

注意:也可以嘗試使用'Input :: get(「url_param」)' – Meysam

+0

@Meysam它返回null。 –

回答

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而不是應用用戶,因爲以這種方式命名它更合乎邏輯。將你做的功能永久地改變一個狀態
  • 增加了一個不是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)), 
       ]); 
} 
+0

!is_null顯示$ username不爲空,但我得到了分析錯誤:語法錯誤,意外的'$ table'(T_VARIABLE),期望函數(T_FUNCTION)。 $查詢給了502錯誤的網關。 –

+0

它們只是佔位符..你只應該將範圍函數注入到模型中。 – Tschallacka

+0

我已經把範圍放在我的模型中,然後傳遞一個變量給它。它工作,變量打印,但當我在查詢中返回它是空的。它如何具有價值並同時爲零? –