Skip to main content
Back to packages
1,208 GitHub stars

topclaudy/compoships

View on GitHub

Description

Compoships offers the ability to specify relationships based on two (or more) columns in Laravel's Eloquent ORM. The need to match multiple columns in the definition of an Eloquent relationship often arises when working with third party or pre existing schema/database

The problem

Eloquent doesn't support composite keys. As a consequence, there is no way to define a relationship from one model to another by matching more than one column. Trying to use where clauses (like in the example below) won't work when eager loading the relationship because at the time the relationship is processed $this->team_id is null.

namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
public function tasks()
{
//WON'T WORK WITH EAGER LOADING!!!
return $this->hasMany(Task::class)->where('team_id', $this->team_id);
}
}

Usage

Using the Awobaz\Compoships\Database\Eloquent\Model class

Simply make your model class derive from the Awobaz\Compoships\Database\Eloquent\Model base class. The Awobaz\Compoships\Database\Eloquent\Model extends the Eloquent base class without changing its core functionality.

Using the Awobaz\Compoships\Compoships trait

If for some reason you can't derive your models from Awobaz\Compoships\Database\Eloquent\Model, you may take advantage of the Awobaz\Compoships\Compoships trait. Simply use the trait in your models.

Note: To define a multi-columns relationship from a model A to another model B, both models must either extend Awobaz\Compoships\Database\Eloquent\Model or use the Awobaz\Compoships\Compoships trait

Syntax

... and now we can define a relationship from a model A to another model B by matching two or more columns (by passing an array of columns instead of a string).

namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class A extends Model
{
use \Awobaz\Compoships\Compoships;
 
public function b()
{
return $this->hasMany('B', ['foreignKey1', 'foreignKey2'], ['localKey1', 'localKey2']);
}
}

We can use the same syntax to define the inverse of the relationship:

namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class B extends Model
{
use \Awobaz\Compoships\Compoships;
 
public function a()
{
return $this->belongsTo('A', ['foreignKey1', 'foreignKey2'], ['ownerKey1', 'ownerKey2']);
}
}

Recent Courses on Laravel Daily

Next.js Basics for Laravel Developers

11 lessons
58 min

Testing in Laravel 13 For Beginners

26 lessons
1 h 41 min read

Laravel 13 Eloquent: Expert Level

41 lessons
1 h 34 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.