F
F
freelancer0072020-04-25 17:40:51
Laravel
freelancer007, 2020-04-25 17:40:51

Laravel not outputting model 1 to 1?

Hi all!
Faced such a moment
There is a model Ticket
id
user_id
status_id
created_at
updated_at

There is a model Claimant
id
ticket_id
info
created_at
updated_at

There is a method in the Ticket model

public function claimant()
    {
        return $this->hasOne(Claimant::class);
    }


Execute code in tinker
$ticket = App\Ticket::find(46)
$ticket->claimant->info

Displays as expected info from Claimant
And if I execute a request
$tickets = App\Ticket::with(['claimant:id,info'])
                      ->where('user_id',704)
                      ->where('status_id', '>', 0)->get();

That brings out
App\Ticket {#917
         id: 46,
         user_id: 704,
         status_id: 1,
         created_at: "2020-04-16 02:03:47",
         updated_at: "2020-04-16 02:03:47",
         claimant: null,
       }

Tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freelancer007, 2020-04-25
@freelancer007

Understood.
I made a mistake when compiling the request,
I had to do this:

$tickets = App\Ticket::with(['claimant:id,ticket_id,info'])
                      ->where('user_id',704)
                      ->where('status_id', '>', 0)->get();

It turned out that the selection should contain a linking field, in my case ticket_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question