0

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);
}
Ali Sharifi Neyestani
  • 4,162
  • 1
  • 14
  • 22
Beusebiu
  • 1,433
  • 4
  • 23
  • 68
  • Which is your "second table"? – Robin Gillitzer Feb 18 '20 at 09:16
  • First one is for persons, the second one are another info about each person,in Register, and I use a FK between them. – Beusebiu Feb 18 '20 at 09:17
  • hi, have you checked [Eager Loading](https://laravel.com/docs/6.x/eloquent-relationships#eager-loading)? you can use `with` to query a model along with its relationships. e.g. `Person::with('register');`. – Bagus Tesa Feb 18 '20 at 09:19

2 Answers2

2

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.

Gamopo
  • 1,600
  • 1
  • 14
  • 22
1

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();
}
Ali Sharifi Neyestani
  • 4,162
  • 1
  • 14
  • 22