表 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);
}
这将返回我需要的所有数据,但是,我需要按表 C 中的一列(ItemValue 模型)对其进行排序。
任何帮助将不胜感激。
您可以将 ->orderBy('TableName', 'desc') 添加到 getAssocBySteamID 函数中。
或者到 Orm() 函数中 ->get() 之前的查询
同样对于 Eloquent 的 QB 中的 Where 子句,您不需要"="符号。你可以在哪里做('steamid',$id)
不要使用静态函数使用作用域。尝试使用如下所示的联接查询:
// 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;
}
检查所有表和字段名称以测试此示例。