了解 Eloquent 一对多关系

Understanding Eloquent One-to-many Relationships

我试图理解 Eloquent 关系,但似乎我在理解它时遗漏了一些东西。我有:

因此是一对多的关系。我试图在 Document 详细信息 table 中显示 'meeting_name' 但出现此错误:

Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)

这是我的代码。

请用代码解决请说明:

app\Document.php 文件:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    protected $fillable = [
        'document_name',
        'document_desc',
    ];

    public function meeting(){
        return $this->belongsTo(Meeting::class);
    }
}

app\Meeting.php 文件:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    protected $fillable = [
        'document_id',
        'meeting_name',
        'meeting_desc',
        'room_no',
        'no_of_invitees',
        'comments'
    ];

    public function documents(){
        return $this->hasMany(Document::class);
    }
}

app\Http\Controllers\DocumentsController.php 文件:

namespace App\Http\Controllers;

use App\Document;
use App\Meeting;
use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index()
    {
        $documents =  Document::all();
        $meetings = Meeting::all();        

        return view('documents.index', compact('documents', 'meetings'));
    }
}

resources\views\documents\index.blade.php 文件:

@foreach($documents as $document)
    <tr>
        <td>{{$document->id}}</td>
        <td>{{$document->document_name}}</td>
        <td>{{$document->document_desc}}</td>
        <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
    </tr>
@endforeach

你的代码有很多问题:

首先:为了使用关系...您必须先加载它...

使用 with('relationName') 方法加载关系...

在索引中:

$documents =  Document::with('meeting')->all();

秒:

 <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->

关系命名为 meeting without s .. not meetings ...

第三名:

在关系中提供外键是有害的做法:

在会议模型中

  public function documents(){
        return $this->hasMany(Document::class,'meeting_id');
    }

在文档模型中:

 public function meeting(){
        return $this->belongsTo(Meeting::class,'meeting_id');
    }

请确保您的文档中有一个列 meeting_id table 在会议中被引用为外键 ID table

有关加载关系的更多详细信息:

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

所以你的 table 搞混了。

您的每个会议只有一个记录,但您的会议 table 中有一个 document_id,您需要为每个文档复制会议记录。

Remove the document_id from your meetings table

Add a meeting_id to your documents table

记得更新你的模型易错数组,否则你不会在 collection 中获得新列。

这应该可以解决您的问题,因为您的关系是正确的。