Laravel + Eloquent ORM:HasManyThrough按TableC.column2排序

3

表A = 库存 | 表B = 物品关联 | 表C = 物品数值

我有表A、B和C。A和B之间是一对一的关系,B和C之间也是一对一的关系。我目前使用HasManyThrough关系来实现这个目标:

public function item(){
    return $this->hasManyThrough('App\ItemValue','App\ItemAssociation','id','id');
}

在我的控制器中:

public function orm(){
    $inventory = Inventory::getAssocBySteamID(76561198124900864)->get();
    $i = 0;
    foreach($inventory as $inv){
        $this->data[$i] = $inv->item()->get();
        $i++;
    }
    return $this->data;
}

对于 Inventory::getAssocBySteamID:

public static function getAssocBySteamID($id){
    return SELF::where('steamid64','=',$id);
}

这会返回我所需的所有数据,但是我需要按Table C中ItemValue模型中的一列进行排序。
非常感谢您的帮助。
2个回答

0

你可以在getAssocBySteamID函数中添加->orderBy('TableName', 'desc')。
或者在Orm()函数中的查询之前添加->get()

此外,在Eloquent的QB中,对于Where子句,您不需要"="符号。您只需执行where('steamid',$id)即可。


0

不要使用静态函数,使用作用域。尝试使用类似这样的联接查询:

// Inventory model method
public function scopeAssocBySteamID($query, $id) {
    $query->where('steamid64', $id)
        ->join('ItemValue'. 'ItemValue.id', '=', 'Inventory.ItemValue_id')
        ->select('Inventory.*')
        ->orderBy('ItemValue.item_price')
}

然后:

public function orm(){
    $inventory = Inventory::assocBySteamID(76561198124900864)->get();
    $i = 0;
    foreach($inventory as $inv){
        $this->data[$i] = $inv->item()->get();
        $i++;
    }
    return $this->data;
}

在测试此示例之前,请检查所有表格和字段名称。


这个可以用,谢谢!但是它仍然没有按照表C(ItemValue)中的列item_price进行排序。 - Nuled
我把它放在上面的编辑中了。请检查一下:->orderBy('ItemValue.item_price') - Filip Koblański
仍然无法工作...它改变了顺序,但与ItemValue.item_price没有任何关系...奇怪 - Nuled
好的,您能给我展示一些item_price的例子,并告诉我这个字段在数据库中是什么类型吗? - Filip Koblański
我可以按照数量排序,但我无法按average_price排序,这就是我所需要的。 - Nuled
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接