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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)