dongpeng7744
2019-01-03 00:50
浏览 53
已采纳

Laravel 5.7 Eloquent关系列表

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: enter image description here

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
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulvyi2172 2019-01-03 01:02
    已采纳

    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');
    }
    
    点赞 评论

相关推荐 更多相似问题