Skip to content
Advertisement

Laravel Model query when foreign is on the other table

I have two models Document(having name as one of the columns) and ApplicationDocument. ApplicationDocument contains the foreign key (docucument_id). I want to fetch records from documents that are related to the applicationDocument and also match the name criteria.

My relationship looks like this in ApplicationDocument

JavaScript

And looks like this in Document:

JavaScript

And my query looks like this:

JavaScript

My query is throwing errors. What am I missing please?

Advertisement

Answer

These code is in trait, you are using Type hinting. However, laravel will assuming the namespace of Builder is AppTraits. So the error occurs.

You can add this line at the top of your trait:

JavaScript

or remove type-hinting Builder.


And by convention, Eloquent will take the “snake case” name of the owning model and suffix it with _id. So by default eloquent will assuming the foreign_key is document_id. However, the foreign_key is doc_id, so you need to specify it.

For ApplicationDocument:

JavaScript

For Document, recommend to use plural method name:

JavaScript

Apply use($appID) for injecting the $appID to closure.

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