如何在Eloquent中按主表字段和枢轴排序?

时间:2015-08-13 22:30:48

标签: laravel laravel-4 eloquent

数据透视表有一个额外的字段:排序顺序的序数。我如何按顺序和romance_color排序?

Inventory::where('item_id', '=', $itemId)
->with('size')
->orderBy('romance_color')
->get();

文档有以下示例:

$users = User::with(array('posts' => function($query)
{
    $query->orderBy('created_at', 'desc');
}))->get();

如何在主表中按字段排序,然后按透视表字段排序?例如,我可以按用户添加日期排序,然后按帖子创建日期排序吗?

你能否提出雄辩的替代解决方案?

谢谢

3 个答案:

答案 0 :(得分:1)

我使用简单的连接和雄辩:

Inventory::where('item_id', '=', '170')
->with('size', 'color', 'item.category')
->join('attribute_value_size_group as gr', 'gr.attribute_value_id', '=', 'size_id')
->orderBy('romance_color')
->orderBy('ordinal')
->select('inventory.*', 'gr.ordinal')
->get()->toArray();

答案 1 :(得分:0)

您可以使用查询构建器:

例如:

 $pivotTable= DB::table('pivot_table')->where('item_id', $itemID)->orderBy('romance_color')->get();

答案 2 :(得分:0)

尝试这个。

 @Override
 public View getView(final int position, final View convertView, ViewGroup parent) {
  View v = convertView;

  final ViewHolder holder;
  if(v == null) {
     v = mInflater.inflate(R.layout.list_item_car, parent, false);
     holder = new ViewHolder();
     holder.txtCarName = (TextView) v.findViewById(R.id.txt_car_name);
     holder.radioGroup = (RadioGroup) v.findViewById(R.id.scale);

     holder.radioGroup.setTag(position);
     v.setTag(holder);


  }
  else {
     holder = (ViewHolder) v.getTag();
  }

  // fill row data
  final Car currentItem = getItem(position);
  if(currentItem != null) {
     holder.txtCarName.setText(currentItem.getCar());
     holder.radioGroup.setTag(currentItem.getAnswer());
  }


  holder.radioGroup.setOnCheckedChangeListener(null);
  holder.radioGroup.clearCheck();

  if(checked.indexOfKey(position)>-1){
     holder.radioGroup.check(checked.get(position));
  }else{
     holder.radioGroup.clearCheck();
  }

  holder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

     @Override
     public void onCheckedChanged(RadioGroup group, int checkedId) {

        String Answer = null;
        if(checkedId>-1){
           checked.put(position, checkedId);


           switch (checkedId) {
              case R.id.a1:
                 Answer = "r1";
                 break;
              case R.id.a2:
                 Answer = "r2";
                 break;
              case R.id.a3:
                 Answer = "r3";
                 break;
              case R.id.a4:
                 Answer = "r4";
                 break;
           }

           db.addListItem(“testCar", Answer, getCurrentTimeStamp());  //<----null object reference happening here


        }else{
           if(checked.indexOfKey(position)>-1)
              checked.removeAt(checked.indexOfKey(position));
        }

     }
     });



  return v;
  }

这与此有些相关。

http://laravel.io/forum/04-17-2014-order-by-pivot-table-attribute-in-eloquent