Ich habe Produkt-und Kategorie-Modelle in meinem Projekt. Produkt gehört zur Kategorie. Seit Produktfremdschlüssel category_id hat, konnte ich leicht die Ausgabe sortiert werden wie so:Laravel Auftrag von verwandten Tabelle
$products = Product::orderBy('category_id', 'asc')->get();
Aber was wollte ich wirklich Produkte nach Kategorie Namen zu sortieren, also habe ich versucht:
$products = Product::with(['categories' => function($q){
$q->orderBy('name', 'asc')->first();
}]);
Aber diese Ausgänge nichts. Als Test habe ich return Product::with('categories')->first();
zurückgegeben und es gibt feine ...
Hier sind die eloquenten Beziehungen.
Produkt
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');
}
}
Kategorie:
class Category extends Model
{
protected $fillable = [
'name'
];
public function products()
{
return $this->hasMany('\App\Product');
}
}
Und der Blick Teil:
@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
Das funktioniert nicht. Und hat keinen logischen Sinn. Produkt kann nur eine Kategorie haben. Ich habe meine Beziehungen in Tinker getestet und sie arbeiten so, wie sie sollten. Modelle sollten nicht das Problem sein – Norgul
Das ist Grammatikproblem, wenn Produkt nur eine Kategorie hat, benenne es nicht als Plural wie Kategorien. Es ist verwirrend – geckob
Ich werde es betrachten, warum es nicht funktioniert – geckob