Skip to content
Advertisement

Laravel one-to-many relationship with different column than primary key

I have following two tables:

JavaScript

There’s a one-to-many relationship between account and projects.

Foreign key in projects table is named account_code instead of account_id.

The issue being project identifier column that is of significance is project_id rather than id in projects table.

Here’s my Account model:

JavaScript

Project model:

JavaScript

I have a row in projects table as:

JavaScript

I tried retrieving account detail that project_id 312 belongs to.

JavaScript

This throws exception:

JavaScript

and with this:

JavaScript

this tried to look into by id field instead of project_id.

How can I solve this without having to write a query?

Advertisement

Answer

The problem here is that get is retrieving you a collection instead of an instance. You can use

JavaScript

instead and that should do the trick.

Hope it helps. Some other solutions are exposed here: Property [title] does not exist on this collection instance

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