【发布时间】:2016-08-19 19:24:50
【问题描述】:
我的项目中有产品和类别模型。产品属于类别。由于 Product 有外键 category_id,我可以像这样轻松地对输出进行排序:
$products = Product::orderBy('category_id', 'asc')->get();
但我真正想要的是按类别名称对产品进行排序,所以我尝试了:
$products = Product::with(['categories' => function($q){
$q->orderBy('name', 'asc')->first();
}]);
但这什么也没输出。作为测试,我返回了return Product::with('categories')->first();,它的输出很好......
这里是 Eloquent 关系。
产品
class Product extends Model
{
protected $fillable = [
'name',
'description',
'price',
'category_id',
];
protected $hidden = [
'created_at',
'updated_at',
];
public function categories()
{
return $this->belongsTo('\App\Category', 'category_id');
}
}
类别:
class Category extends Model
{
protected $fillable = [
'name'
];
public function products()
{
return $this->hasMany('\App\Product');
}
}
还有视图部分:
@foreach ($products as $product)
<tr>
<td>{!! $product->categories->name !!}</td>
<td>
@if(!empty($product->picture))
Yes
@else
No
@endif
</td>
<td>{!! $product->name !!}</td>
<td>{!! $product->description !!}</td>
<td>{!! $product->price !!}</td>
<td>
<a href="{{ url('/product/'.$product->id.'/edit') }}">
<i class="fa fa-fw fa-pencil text-warning"></i>
</a>
<a href="" data-href="{{route('product.destroyMe', $product->id)}}"
data-toggle="modal" data-target="#confirm-delete">
<i class="fa fa-fw fa-times text-danger"></i>
</a>
</td>
</tr>
@endforeach
【问题讨论】:
标签: php laravel sorting html-table