Yeah thats not possible when using different connections as laravel will just add the count query to the main query.
You will need to manually get the counts from the mysql connection and add it to the result of the customers query
Hi, I have a Customer model with a configured SQL Server connection and a hasMany relationship to a Project model with a configured MySQL connection.
Relationship retrieval works fine. Problem is when calling withCount('projects') on the Customer model the sql eloquent generates uses the MySQL syntax with '`' which results in a syntax error on the SQL Server connection since we are comming from the Customer model.
Here are the models, the Controller and the resulting error message. Any ideas how to properly implement/avoid this?
class Customer extends Model
{
protected $connection = 'sqlsrv';
public function projects(): HasMany
{
return $this->hasMany(Project::class, 'customer_id', 'id');
}
}
class Project extends Model
{
protected $connection = 'mysql';
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class, 'customer_id', 'id');
}
}
class CustomerController extends Controller
{
public function index(): Response
{
$customers = Customer::withCount(['projects'])->get();
return Inertia::render('Customer/List', [
'customers' => new CustomerResourceCollection($customers),
]);
}
}
SQLSTATE[42000]: [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Incorrect syntax near ''.(Connection: sqlsrv, SQL: select [customers].*, (select count(*) from laravel.laravel.projectsasprojectswherecustomers.Kundennummer=projects.customer_id`) as [projects_count] from [customers])
Yeah thats not possible when using different connections as laravel will just add the count query to the main query.
You will need to manually get the counts from the mysql connection and add it to the result of the customers query
Please or to participate in this conversation.