public function connections()
{
$relation = $this
->belongsToMany(static::class, 'connections', 'requestor_id', 'requested_id')
->withTimestamps();
/// delete the already built inner join
$relation
->getQuery() // Eloquent\Builder
->getQuery() // Query\Builder
->joins = [];
/// create a new inner join with the needed or condition
$relation->getQuery()->getQuery()->join('connections', function($join)
{
$join->on('users.id','=','connections.requestor_id');
$join->orOn('users.id','=','connections.requested_id');
});
return $relation;
}
Here's the full version, rebuilding the where clause and preventing the user to appear in the list of connections:
public function allConnections()
{
$relation = $this
->belongsToMany(static::class, 'connections', 'requestor_id', 'requested_id')
->withTimestamps();
// Delete the already built "inner join".
$relation
->getQuery() // Eloquent\Builder
->getQuery() // Query\Builder
->joins = [];
// Delete the already built "where".
$relation
->getQuery()
->getQuery()
->wheres = [];
// Delete all bindings.
$relation
->getQuery()
->getQuery()
->setBindings([]);
// Create a new inner join with the needed or condition.
$relation->getQuery()->getQuery()->join('connections', function($join)
{
$join->on('users.id','=','connections.requestor_id');
$join->orOn('users.id','=','connections.requested_id');
});
// Create a new where with both conditions
$relation->where(function($query)
{
$query->where('connections.requestor_id', $this->id);
$query->orWhere('connections.requested_id', $this->id);
});
// A user is not connected to itself
$relation->where('users.id', '!=', $this->id);
return $relation;
}