Reputation: 229
I have a Laravel 5.2
one-to-many relation
and I want to return the model and put a condition to relation.
I've tried this:
$categories = Category::with(['descriptions' => function($d) use ($default_language) {
$d->where('language_id', $default_language->id);
}])->get();
It work fine, I just want something else: the relation should not be a collection or array, just a simple object. I want to do something like
$d->where('language_id', $default_language->id)->first();
, just in this case first()
is not working. Any ideas?
EDIT
Actually first()
is not working properly, it returns first description just for the first object returned, for others it return nothing.
Upvotes: 3
Views: 1790
Reputation: 3045
Try this:
$categories = \Jobinja\CMS\Blog\Models\Category::with([
'descriptions' => function ($q) use ($defaultLanguage) {
return $q->where('language_id', $defaultLanguage->id)->take(1);
}
])
->get()
->map(function ($item) {
if ($item->descriptions->isEmpty() === false) {
$item->description = $item->descriptions->first();
}
return $item;
});
and get to description:
foreach ($categories as $category) {
$description = $category->description;
}
Upvotes: 2
Reputation: 545
I can say to use instead of first()
find()
and give it the language_id
or $default_language->id
and this will try to find in the table first the column id
and assign the value. If you have different id column name give it to the find like find(['your_column_name' => '<your_value'])
.
If you want array to something like ->toArray(). You can test different scenarios in tinker. php artisan tinker
Here is a link to document this -> https://laravel.com/docs/5.3/eloquent#retrieving-single-models
Upvotes: 0
Reputation: 163778
You can't do that but you can use first()
on a collection later, for example in a view:
@foreach ($categories as $category)
{{ $category->descriptions->first()->name }}
@endforeach
Upvotes: 0