0

I have a table named as users:

id |  name |  email  

and attachment table

id |  file_name   |  user_id  |  type 
1    filename1.jpg      56         7
2    filename2.jpg      56         7
3    filename3.jpg      57         7
4    filename4.jpg      56         6

I'm fetching data from users table like:

 $data = Users::find($id);

but I want to get attachment table data also with users table. But I want to match user_id and type also, where user_id matches and type = 7 only those rows should return.

1 Answer 1

2

First create Attachment model php artisan make:model Attachment

Create a hasMany relationship to 'Attachment' at the 'Users' model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{
    public function attachments()
    {
        return $this->hasMany(Attachment::class);
    }
}

Then you can query like

$data = Users::with(['attachments' => function ($query) {
    $query->where('type', 7);
}])->find($id);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.