jeudi 23 mai 2019

Eloquent With A One to One 'Like' Relationship

I currently have an Eloquent Model that I have tried to simplify for this example and has a similar structure to the below.

class Student extends Model {

    public function classes()
    {
        return $this->hasMany('App\Classes', 'class_code','code');
    }

    public function events()
    {
        return $this->hasOne('App\Events', 'event_code', 'code');
    }

}

Every student has an assigned code. Hence a student can be matched to classes or event in a one to many / one relationships via this code. The issue is the relationship of the event. The code is slightly different.

In classes, the code will be 11-ABCD.00

For events, the code is: 11-ABCD

The decimal point is missing in the event code but otherwise, the code is the same. The decimal point simply allows for finer sub-divisions. For relationships, it does not matter and may not always exist i.e. A student may not have a class or event related to them.

I can manually retrieve an Event record like this:

class Student extends Model {

public function events($code)
{        
        $code = explode('.', $code);

        if(count($code) > 0)
        {    
            $code = $code[0];
        }

        return Event::where('code', $code)->first();
    }
}

But this isn't in the true spirit of eloquent when I want to retrieve an entire collection e.g.

$results = Student::with('events')->first();

In short, can I design the relationship of the event to automatically take the key 'code' and strip it so that I can retrieve the records that are relevant?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire