Laravel:将参数传递给关系函数?

use*_*318 9 php laravel

有可能以某种方式将参数传递给关系函数吗?

我目前有以下内容:

public function achievements()
{
     return $this->belongsToMany('Achievable', 'user_achievements')->withPivot('value', 'unlocked_at')->orderBy('pivot_unlocked_at', 'desc');
}
Run Code Online (Sandbox Code Playgroud)

问题是,在某些情况下,它不会获取unlocked_at列并返回错误.

我试过做类似的事情:

public function achievements($orderBy = true)
{
$result = $this->belongsToMany (...)
if($orderBy) return $result->orderBy(...)
return $result;
}
Run Code Online (Sandbox Code Playgroud)

称之为:

$member->achievements(false)->(...)
Run Code Online (Sandbox Code Playgroud)

但这不起作用.有没有办法将参数传递给该函数或以任何方式检查是否pivot_unlocked_at正在使用?

小智 11

那么我所做的只是为我的模型添加新属性,然后将我的条件添加到该attirbute,只需这样做.

Class Foo extends Eloquent {
    protected $strSlug;

    public function Relations(){
         return $this->belongsTo('Relation','relation_id')->whereSlug($this->strSlug);
    }
 }

 Class FooController extends BaseController {
     private $objFoo;


     public function __construct(Foo $foo){
         $this->objFoo = $foo
     }

     public function getPage($strSlug){
        $this->objFoo->strSlug = $strSlug;
        $arrData = Foo::with('Relations')->get();
        //some other stuff,page render,etc....
     }
 }
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以简单地创建一个范围,然后在必要时将其添加到构建器实例中。

例子:

用户名

public function achievements()
{
    return $this->hasMany(Achievement::class);
}
Run Code Online (Sandbox Code Playgroud)

成就.php

public function scopeOrdered(Builder $builder)
{
    return $builder->orderBy(conditions);
}
Run Code Online (Sandbox Code Playgroud)

然后在使用时:

//returns unordered collection
$user->achievements()->get();

//returns ordered collection
$user->achievements()->ordered()->get();
Run Code Online (Sandbox Code Playgroud)

您可以在Eloquent 文档 中阅读有关范围的更多信息。