Skip to content

Instantly share code, notes, and snippets.

@antonioribeiro
Last active March 9, 2022 05:20
Show Gist options
  • Save antonioribeiro/6f7a4c9a1336f798fa65 to your computer and use it in GitHub Desktop.
Save antonioribeiro/6f7a4c9a1336f798fa65 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