jeudi 28 janvier 2016

Manage multiple relations to same column and table in Laravel

I am new in Laravel (5.1) and i try to understand the conventions and concepts. I have two different relationship types on the same tables and the same column and i use Laravels Eloquent.

Example: I collect browser fingerprints including their active screen resolution and the available screen resolutions. That points in the following:

  • two tables: fingerprints, resolutions
  • two columns: active_resolution, available_resolutions
  • two relationships: one-to-many for active_resolution, many-to-many for available_resolutions

Here the example of the two models:

class Resolution extends Model {
    public function fingerprints2() {
        return $this->belongsToMany(Fingerprint::class);
    }
    public function fingerprints() {
        return $this->hasMany(Fingerprint::class);
    }
}

class Fingerprint extends Model {
    public function active_resolution() {
        return $this->belongsTo(Resolution::class);
    }

    public function available_resolutions() {
        return $this->belongsToMany(Resolution::class);
    }
}

I query the data based on the Fingerprint model, where i ask for the two resolution types. So i use the methods active_resolution() and available_resolutions. For this, everything is fine and works.

But if you look at the Resolution model, i have a method name conflict. I both time have a fingerprints method to set the two relations which return in this case the same data (i think, both time i get "many fingerprints", so it should be fingerprints). If i maybe want to use them later, i have to access them over fingerprints or fingerprints2 which is kind of ugly style. Is there an opportunity to set both relations in the same method fingerprints?

For example, i know such kind of concepts from CakePHP, where a model looks like this:

class Resolution extends AppModel {
    public $hasAndBelongsToMany = array('Fingerprint' => [...]);
    public $hasMany = 'Fingerprint';

    // do cool stuff here without method name conflicts
}

There i have no problem with multiple relationships and no conflicted method names for the same use. Is there maybe something similar or another solution?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire