Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahednur/7fae4e199a140ba6fd9d3179ed1d55b5 to your computer and use it in GitHub Desktop.
Save shahednur/7fae4e199a140ba6fd9d3179ed1d55b5 to your computer and use it in GitHub Desktop.
Add more conditions to your Laravel Relations
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment