I'm using Laravel 8. I want to create a relationship to get a user's active picture or most recent with some conditions to get only one picture.
Here is my model
user
- id
- name
picture
- id
- user_id
- type -> nullable
- created_date
- expiry_date
class User extends Model
{
public function activePictureOrMostRecent()
{
return $this->hasOne(Picture::class, 'user_id')...
}
}
In my relationship I want to separate my pictures in 2 categories, typed picture
and untyped picture
so if type is null then it's an untyped picture
.
So now let's talk about the conditions about how to get the active picture:
First I'll sort by created_date desc
and then:
- If there is an active TYPED picture by the date (if created_date is <= today and expiry_date >= today) I take it
- Else if I don't have active TYPED picture I want to take the active UNTYPED picture (same condition with the date)
- Else if I don't have active UNTYPED picture I want the most recent TYPED picture
- And finally if I have no most recent TYPED picture I take the most recent UNTYPED picture
It is possible to create this relationship ?