I am currently using the Spatie media library and I have created my own custom class as follows:
use Spatie\MediaLibrary\Models\Media as BaseMedia;
class TrybzMedia extends BaseMedia
{
protected $table = 'media';
protected $appends = ['url'];
public function getUrlAttribute()
{
return $this->getUrl();
}
}
I have a User class where I have defined a polymorphic relationship:
public function avatar()
{
return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar');
}
There could be multiple images uploaded so what I am trying to achieve is get the last record for the relationship. I have attempted the following with no luck:
public function avatar()
{
return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar')->last();
}
I want to contain all the code within the definition of the relationship. Is that possible?
CodePudding user response:
You can try using ->limit(1) like :
public function avatar()
{
return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar')->orderBy('put_column_name_here', 'DESC')->limit(1);
}
You can get last record.:)
CodePudding user response:
The following works:
public function cover()
{
return $this->morphMany(TrybzMedia::class, 'model')
->where('collection_name', '=', 'cover')
->take(1)
->latest();
}
CodePudding user response:
You can try with order by and first to get the last or first record.
public function avatar()
{
return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar')->orderBy('put_column_name_here', 'DESC')->first();
}