Beusebiu
Beusebiu

Reputation: 1513

Laravel get value from 2 column with relationship one to one

I have 2 tables and have relationship one to one. Second table use a FK from first one, and I want to display a list with all values .

public function index(Request $request)
{
   $listOfPersons = new Person();
   $listOfRegisters = new  Register();

   $listOfRegisters->listOfPersons()->associate();
   return $listOfRegisters;
}

In Register Model

public function people(){
    return $this->hasOne(Person::class);
}

In Person Model

public function register(){
    return $this->hasOne(Register::class);
}

Upvotes: 0

Views: 485

Answers (2)

Ali Sharifi Neyestani
Ali Sharifi Neyestani

Reputation: 4388

I think you have to use leftjoin. (not foreach and php loop)

Because:

The alternative of handling this inside your PHP code with a foreach loop is unattractive for several reasons. First, you would probably need to bring in all information from both tables, which is wasteful from both a memory and network usage point of view. Then, even after you have brought in the data, you would be relying on PHP to perform the join. PHP wasn't really designed for in house database operations, and cannot use something like an index to speed up the process.

So you can write your query like:

User::leftJoin('register', 'register.user_id', '=', 'id');

However, I prefer to add a scope in my model for this situation

<?php

class User extends Authenticatable
{
    public function scopeRegister($builder)
    {
       $query = $query->leftJoin('register', 'register.user_id', '=', 'id');
       return $query;

    }

and in my controller

public function index(Request $request)
{
    $records = User::register()->get();
}

Upvotes: 1

Gamopo
Gamopo

Reputation: 1598

If you just want a list with all pairs of values, it should be enough with this code:

public function index(Request $request)
{
    $registers = Register::all();
    $list = [];
    foreach($registers as $register){
        array_push($list,['register'=> $register, 'person'=>$register->people]);
    }
    return $list;
}

But remember you can just have the list of registers and access the person via the relationship. Moreover, you should change the hasOne relationship to belongsTo in register.

I hope that helps.

Upvotes: 2

Related Questions