Как присоединиться к таблице в Laravel 5.8 - PullRequest
0 голосов
/ 19 июня 2019

У меня есть 2 пользователя таблицы и данные.

в таблице пользователей есть:

id | имя | электронная почта | и т. д.

в таблице данных есть:

id | user_id | no_data | и т. д.

я создаю модель данных, как это

public function users()
{
    return $this->HasMany(\App\User::class ,'id');
}

мой контроллер:

public function pns()
{
    $data = Data::get();

    //DB::table('data')
        //->join('users','data.user_id','=','users.id')
        //->where(['user' => 'something', 'otherThing' => 
         // 'otherThing'])
        //->get(); // i trying to join this table but still error 


    return view('admin.data',['data' => $data]);
}

Теперь я хочу показать данные представления в таблице:

на мой взгляд лезвие:

 <th>No </th>
 <th>id </th>
 <th>Name </th>
 <th>email </th>


  @php
  $no=0;
  @endphp
  @foreach ($data as $i)
  <tr>
   <td class=" ">{{ ++$no }}</td>
   <td class=" ">{{ $i->user_id}}</td>
   <td class=" ">{{ $i->users->name}}</td>
   <td class=" ">{{ $i->email}}</td>
  </tr>

этот user_id показывается, но это «имя» не отображается и выдается ошибка:

Свойство [имя] не существует в этом экземпляре коллекции.

отредактировал мой дд ($ data)

#attributes: array:18 [▼
    "id" => 1
    "user_id" => 6
    "email" => 'q@gmail.com'
    //etc
    "created_at" => "2019-06-18 17:27:54"
    "updated_at" => "2019-06-18 17:27:54"
  ]

Ответы [ 5 ]

1 голос
/ 19 июня 2019

Предполагается, что ваш один пользователь может иметь несколько данных. Вот мое решение

Для Модал пользователя

class User extends Authenticatable
{

  <YOUR OTHER CODES HERE>

  public function datas(){
     return $this->hasMany(Data::class,'user_id','id');
  }
}

Для Data.php [Модальный режим данных]

class Data extends Model{

 <YOUR OTHER CODE>

 public function userDetail(){
   return $this->belongsTo(User::class,'user_id','id');
 }
}

Из вашего контроллера:

 $data = Data:with('userDetail')->get();
 echo '<pre>';
 print_r($data->toArray()); // This will give you an array of data with user details. 
0 голосов
/ 19 июня 2019

используйте hasOne в вашей пользовательской модели

public function data()
{
return $this->hasOne('App\Data', 'user_id');
}

// controller

return view('admin.data')->with($data);
0 голосов
/ 19 июня 2019

Используйте этот запрос

DB::table('data')
->join('users','data.user_id','=','users.id')
->where('user_id','=',1)
// Here you can also add more wheres
// But make sure where column exists in one of queried table i.e in 
// users | data 
->select([
    'no',
    'user_id as id',
    'name',
    'email'   
])
->get(); // i trying to join this table but still error 
0 голосов
/ 19 июня 2019

Вам необходимо обновить ваши отношения в модели данных

public function users()
{
    return $this->hasMany(\App\User::class ,'user_id');
}

должно быть hasMany не HasMany и user_id not id

Тогда используйте это: $data = Data::with('users')->get();

0 голосов
/ 19 июня 2019

сделать это $data = Data::with('users')->get();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...