Skip to content
Advertisement

Select specific column from morph relation according to type in Laravel

I am trying to write a query that selects columns from a model then selects some columns from a morph relationship table. But I have no idea to select columns, and relation tables have different columns. So some column has no slug, some have.

JavaScript

Models

JavaScript

How can I select specific columns from morph relation with checking morph type? I am using Laravel version 8.

Advertisement

Answer

The polymorphic relation is something the Eloquent aware of, and DBMS hasnot implemented this feature in it. so there cannot be a sql query which join a table to another tables based on the morph column.

so you have to use distinct queries for every polymorphic join relation on your models:

JavaScript

if you want a common interface to use one of these dynamically. you can use:

JavaScript

I am not sure which columns you want to response, but as i can guess from your question, I suppose you want id and slug from both models.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement