rifki's avatar
Level 3

Eloquent subquery ordering different database connections?

I have two models with different database connections.

---

class Foo extends Model
{
	$connection = 'sqlite';

	$table = 'foos';

	public function bar()
	{
		$this->belongsTo(Bar::class);
	}
}

class Bar extends Model
{
	$connection = 'mysql';

	$table = 'bars';

	public function foos()
	{
		$this->hasMany(Foo::class);
	}
}

The basic relationship works just fine, for example, I can query Bar by calling $foo->bar() but when I'm trying to order Foo by Bar columns like this:

Foo::orderByDesc(
	Bar::select('created_at')->whereColumn('id', 'foos.bar_id')->limit(1)
)->get()

It returns Property [from] does not exist on the Eloquent builder instance..

Any ideas on how to get it to works?

0 likes
2 replies
tinkerbell's avatar

change get to first

Foo::orderByDesc(
	Bar::select('created_at')->whereColumn('id', 'foos.bar_id')->limit(1)
)->first()

Because get will always return a collection even if your query could only ever return a single row and first returns a single model instance

rifki's avatar
Level 3

Thank you for your answer, unfortunately, it doesn't work. I tried with get, first, and paginate.

In real usage, I have a data-table for Foo and trying to sort the order by its Bar creation date, so I should go with either get or paginate.

I do have other Foo relationships and I'm also using the same subquery method as above for sorting, they are works just fine since they are using the same database connection.

Example other relation that works:

class Foo extends Model
{
	$connection = 'sqlite';

	$table = 'foos';

	public function bar()
	{
		$this->belongsTo(Bar::class);
	}

	public function baz()
	{
		$this->belongsTo(Baz::class);
	}
}

class Bar extends Model
{
	$connection = 'mysql';

	$table = 'bars';

	public function foos()
	{
		$this->hasMany(Foo::class);
	}
}

class Baz extends Model
{
	$connection = 'sqlite';

	$table = 'bazzes';

	public function foos()
	{
		$this->hasMany(Foo::class);
	}
}

Notice that Foo has the same database connection as Baz and sorting with code below works fine:

Foo::orderByDesc(
	Baz::select('created_at')->whereColumn('id', 'foos.baz_id')->limit(1)
)->get()

Please or to participate in this conversation.