Home > Software engineering >  How to order elements from a third table in laravel eloquent?
How to order elements from a third table in laravel eloquent?

Time:01-26

I don't know how to do this. I have a table of supliers, with documents, and each document has a type of document with names.

Supliers
    id
    name

Documents
    id
    file
    suplier_id
    document_type_id
    upload_date

Document_types
    id
    name

supliers->hasMany('documents')->orderBy('upload_date')

documents->belongsTo('document_types')

I need to retrieve the collection of documents by the names of the types of documents... something like this:

supliers->hasMany('documents')->orderBy('document_types.name')->orderBy->('upload_date')

Thanks a lot!!

CodePudding user response:

Assuming that you have defined all your model relationships properly, something like this should work:

$suplier->documents()
    ->select('documents.*')
    ->join('document_types', 'document_types.id', '=', 'documents. document_type_id')
    ->orderBy('document_types.name')
    ->orderBy('documents.upload_date')
    ->get()

While I don't know the full scope of this work, one thing I'd like to point out is that if the document types are a pre-defined set of types, it doesn't necessarily have to be on a separate table. It could just be an enum stored on the documents table itself which improves both querying and performance.

  • Related