Laravel 7 用户与列表之间的关系无效

Laravel 7 Relation between User and Listing not working

我正在尝试与我的 laravel 应用程序中的列表和用户建立关系。但是这种关系不起作用。这是我的代码:

Listing.php(型号)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Listing extends Model
{
    public function user() {
        return $this->belongsTo('App\User');
    }
}

User.php(型号)

public function listing() {
    return $this->hasMany('App\Listing');
}

DashboardController.php(控制器)

public function index()
    {
        $user_id = auth()->user()->id;
        $user = User::find($user_id);

        return view('dashboard')->with('listings', $user->listings);
    }

和dashboard.blade.php(查看)

<div class="panel-body">
                        {{ dd($listings) }}
                        @if(count($listings))
                            <table class="table table-stripped">
                                <tr>
                                    <th>Company Name</th>
                                    <th>Address</th>
                                </tr>
                                <tr>
                                    @foreach($listings as $listing)
                                        <tr>
                                            <td>{{ $listing->name }}</td>
                                            <td>{{ $listing->address }}</td>
                                        </tr>
                                    @endforeach
                                </tr>
                            </table>
                        @endif
                    </div>

但它没有使用 'listings' 变量传递数据。它显示 'listings' 变量为 NULL。

你们能帮帮我吗?

我觉得你漏掉了什么

public function index()
{
    $user = User::find(auth()->id());

    // $user->listings or $user->listing ? because in User.php it's listing not listings

    return view('dashboard')->with('listings', $user->listing);
}

最佳实践是在关系中添加外键 像这样:

public function user() {
        return $this->belongsTo('App\User' , 'id');
    }