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

public function document()
    {
        return $this->belongsTo('AppModelsDocument', 'doc_id');
    }

And looks like this in Document:

public function applicationDocument()
    {
        return $this->hasMany('AppModelsApplicationDocument');
            
    }

And my query looks like this:

$previousDoc= Document::whereHas('applicationDocument', function (Builder $query) {
                    $query->where('application_id', $appID);
                })->where('name', $name)->get();

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:

use IlluminateDatabaseEloquentBuilder;

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:

public function document()
{
     return $this->belongsTo('AppModelsDocument', 'doc_id');
}

For Document, recommend to use plural method name:

public function applicationDocuments()
{
    return $this->hasMany('AppModelsApplicationDocument', 'doc_id', 'id');

}

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

$previousDoc= Document::whereHas('applicationDocuments', function (Builder $query) use ($appID) {
                    $query->where('application_id', $appID);
                })->where('name', $name)->get();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement