0

因此,我尝试使用以下方法添加从相关表中获取特定数据,但我不知道这是否是正确的方法。这是它的样子。

public function  transspecific($lid){
    return $this->belongsTo('raplet\Keepertrans')->where("lang_id", $lid);
}

然后我尝试从中获取数据

dd($akeeper->transspecific($akeeper->id));

它不像有任何东西,但是当我dd("hello")在模型中输入时,它可以工作。很明显我的关系背景有问题

4

2 回答 2

1

您正在尝试做的是添加一个 [laravel 中的动态范围][1] 模型,这完全没问题。除非您需要声明与关系方法分开的范围。

关系:

public function keepertrans(){
    return $this->belongsTo('raplet\Keepertrans');
}

范围:

public function transspecific($lid){
    return $this->keepertrans()->where("lang_id", $lid);
}

然后您可以使用 a 调用范围get()来执行查询生成器:

(SomeOtherRelatedModel::first())->transspecific($someId)->get();
于 2019-02-11T22:51:18.937 回答
1

The methods available in Eloquent model for relationship are different than what you need. Whenever you need to add a custom function which internally adds some filters to your query (builder), you need to use scopes

The generic rule of scope function is scope + yourfunction

In your case you will need to create scopeTranspecific function.

Each scope gets the first argument as builder which you update inside the function. The later arguments are optional.

public function scopeTranspecific($query, $lid){

    return $query->keepertrans()->where("lang_id", $lid);
}

And then you can use it :

Model::where('column1' , 'value')->transpecific($id)->get()

If you just dump it without ->get() you will get the query builder instance. You will have to do ->get() to get the data

于 2019-02-11T23:53:00.963 回答