【问题标题】:Laravel + Eloquent ORM: HasManyThrough OrderBy TableC.column2Laravel + Eloquent ORM: HasManyThrough OrderBy TableC.column2
【发布时间】:2016-08-21 22:59:00
【问题描述】:

表 A = 库存 |表 B = ItemAssociation |表 C = ItemValue

我有表 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 模型对其进行排序。

任何帮助将不胜感激。

【问题讨论】:

    标签: php database laravel orm eloquent


    【解决方案1】:

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

    对于 Eloquent 的 QB 中的 Where 子句,您也不需要“=”符号。你可以做 where('steamid',$id)

    【讨论】:

      【解决方案2】:

      不要使用静态函数使用范围。尝试使用这样的连接查询:

      // 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 列排序。
      • 我把它放在上面的编辑中。检查你是否拥有它:->orderBy('ItemValue.item_price')
      • 还是不行……它改变了顺序,但是和ItemValue.item_price没有任何关系……奇怪
      • 好的,你能给我看几个 item_price 的例子,告诉我这个字段在数据库中是什么类型吗?
      • 看这里:screenshot,它是数据库中的一个数值:average_price NUMERIC(8,2),
      猜你喜欢
      • 2016-09-24
      • 2014-08-14
      • 2014-10-31
      • 2020-03-07
      • 2020-10-14
      • 2016-09-26
      • 2015-06-17
      • 2019-03-29
      • 1970-01-01
      相关资源
      最近更新 更多