belongsTo 后获取不到数据,不看教程实战后 就失败了!!!

项目需求

用户表
用户提交日志表

展示用户提交的日志列表

定义一个 日志模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Reportlog extends Model
{
    //
    protected $table = 'reportlog';

    protected $fillable = [
        'today_job', 'tomorrow_job', 'desc'
    ];

    public function user(){
        return $this->belongsTo(User::class);
    }
}

自带的User模型 【没有改动】

日志数据库设计

        Schema::create('reportlog', function (Blueprint $table) {
            //
            $table->bigIncrements('id');
            $table->smallInteger('users_id');
            $table->string('today_job','1024');
            $table->string('tomorrow_job','1024');
            $table->string('desc','1024');
            $table->timestamps();
        });

控制器代码

<?php

namespace App\Http\Controllers\Admin;

use App\Models\Reportlog;
use Carbon\Carbon;

use App\Http\Controllers\Controller;

class ReportlogController extends Controller
{
    public function index(Reportlog $reportlogs){
        //直接通过依赖注入的方式 把变量赋值到模板中
        return view('admin.reportlog.index',compact('reportlogs'));
    }
}

模板中页面展示

第一次测试数据是否循环出来了

//1.发现取到了内容 成功的循环出来
@foreach($reportlogs->all()  as $reportlog)
        测试内容
@endforeach

{{dd("die")}}

第二次测试实际表单中的数据

@foreach($reportlogs as $reportlog)
        {{$reportlog->today_job}}
@endforeach

{{dd("die")}}

直接报错了

Laravel

我还想 下面获取用户的姓名 估计直接死掉了

@foreach($reportlogs as $reportlog)
        {{$reportlog->user-name}}
@endforeach

请问是哪个地方写错了吗?

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

外键users_id改为user_id

4年前 评论
liuhaiqiang999 (楼主) 4年前
liuhaiqiang999 (楼主) 4年前
讨论数量: 4
    public function user(){
        return $this->belongsTo(User::class)->withDefault();
    }
4年前 评论
liuhaiqiang999 (楼主) 4年前

外键users_id改为user_id

4年前 评论
liuhaiqiang999 (楼主) 4年前
liuhaiqiang999 (楼主) 4年前
jaak

一眼就看到了users_id 没有用过复数的形式,有点扎眼 😂

4年前 评论

我写 Laravel 的时候,关联关系习惯把参数都写上。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!