我有一个给定的表结构:
// table: examples
+ -- + ---- +
| id | name |
+ -- + ---- +
| 1 | Test |
| 2 | Test |
+ -- + ---- +
// table: example_data
+ -- + --------------- + ------------------ + --- + ----------------- +
| id | example_data_id | exmaple_data_type | key | value |
+ -- + --------------- + ------------------ + ------------|---------- +
| 1 | 1 | AppModelsExample | external | 1 |
| 2 | 1 | AppModelsExample | otherKey | string |
| 3 | 2 | AppModelsExample | external | 0 |
+ -- + --------------- + ------------------ + ----------- + --------- +
// Example Model:
public function daten()
{
return $this->morphMany(ExampleData::class, 'example_data');
}
// ExampleData Model:
public function example_data()
{
return $this->morphTo();
}
如何按"值"排序我的例子在"example_data"与key = "external"?
$examples = Example::with('daten')
->orderBy(***value from external in daten***) // something like this 'Example->daten->key="external" ==> orderBy Example->daten->value'
->paginate($request->total);
是否可以使用orderBy和callback?回调怎么样?
这是否回答了你的问题:
$examples = Example::with(['daten' => function($query) {
$query->orderBy('key', 'asc');
}])
->paginate($request->total);
这将按升序排列key
列。如果您只想要key
等于external
的记录,您可以这样做:
$examples = Example::with(['daten' => function($query) {
$query->where('key', 'external');
$query->orderBy('value', 'desc');
}])
->paginate($request->total);
按value
列排序。