简体   繁体   中英

Laravel 5.7 Eloquent Relation for listing

i am trying to get dataset with join, and i wanna do it using eloquent and automatically without no manual query. I did the relations too but when i try to list the data joined, somehow it does it otherway around.

Laravel version 5.7 MySQL database

UPDATED, added the database schema. my_tab3s table: my_tab3s

mytab1 table: 在此处输入图片说明

Error:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'myTab1.my_tab3_id' in 'where clause' (SQL: select * from myTab1 where myTab1 . my_tab3_id in (1, 2))"

myTab3.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class myTab3 extends Model
{
    //
    protected $table = 'my_tab3s';
    public $timestamps = true;


    protected $fillable = [
    'coolField',
    'muhCurrentDate',
    'rast',
    'myTab1_id'
  ];


    public function myTab1(){
        return $this->hasOne('App\myTab1');
    }
}

myTab1.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class myTab1 extends Model
{
    //
    public function scopeBigger($query){
        return $query->where('id','>','1');
    }
    public function scopeHasLetterZ($query){
        return $query->where('someField','like','%z%');
    }

    public function gimmeAll(){
        return myTab1::All();
    }
    protected $table = 'myTab1';
    public $timestamps = true;

    protected $fillable = [
    'someField'
  ];


    public function myTab3(){
        return $this->belongsTo('App\myTab3');
    }
}

myTab3Controller.php INDEX method

 public function index()
    {

        /*$dataSet = myTab3::All();*/
        //$dataSet->myTab1()->get();
        $dataSet = myTab3::with('myTab1')->get();
        return view('myTab3.index',compact('dataSet'));
    }

view part

@foreach($dataSet as $data)
        <tr>
            <td>{{$data->id}}</td>
            <td>{{$data->coolField}}</td>
            <td>{{$data->muhCurrentDate}}</td>
            <td>{{$data->created_at}}</td>
            <td>{{$data->updated_at}}</td>
            <td>{{$data->rast}}</td>
            <td>{{$data->myTab1->someField}}</td>
        </tr>
        @endforeach

It's hard to say without the database but i think you reverse your relationships, it shoud be a belongsTo for myTab3 and hasOne for myTab1

EDIT:

try with :

public function myTab1(){
    return $this->belongsTo('App\myTab1', 'myTab1_id');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM