dongpeng7744 2019-01-03 00:50 采纳率: 100%
浏览 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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助