How to specify Laravel relationships based on two (or more) columns (composite keys)
In Laravel Eloquent ORM, there is no way to define a relationship from one model to another by matching more than one column.
For instance, if you want to do something as the below with eager loading, the $this->blog_id
will be null while processing
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function posts()
{
//WON'T WORK WITH EAGER LOADING!!!
return $this->hasMany(Post::class)->where('blog_id', $this->blog_id);
}
}
I faced this problem and tried many approaches and it would not work till I found the package that works perfectly for me.
you can check the package out with the below link.
https://github.com/topclaudy/compoships
There is no need to duplicate how to use the package here cos the package docs are explanatory enough.