【问题标题】:Laravel 6 database relationshipsLaravel 6 数据库关系
【发布时间】:2020-03-02 17:25:49
【问题描述】:

我不太擅长这个问题。

我有两张桌子。买家和追踪者。

在跟踪器表中我有这些列

id, buyer_id, style_name

买家表是

id, buyer_name

当我检索和显示跟踪器列表时,我也希望能够显示买家名称。

在我的 Buyer.php 模型中

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tracker extends Model
{
    /**
     * The attributes that are mass assignable.
     *  
     * @var array
     */
    protected $table = 'trackers';

    protected $fillable = [
        'buyer_id',
        'style_name',
    ];

    public function buyer()
    {
        return $this->hasOne('App\Buyer');
    }
}

我使用工匠修补程序进行测试。所以,代码是;

$tracker = Tracker::find(1)->buyer;

但我收到此错误

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'buyers.tracker_id' in 'where clause' (SQL: select * from `buyers` where `buyers`.`tracker_id` = 1 and `buyers`.`tracker_id` is not null limit 1)'

它在买家表中寻找一个 tracker_id,但我只是使用它的 id 检索一个。我做错了什么?

这是trackers的迁移文件

public function up()
{
    Schema::create('pattern_room_trackers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('buyer_id');
        $table->string('style_name');

        $table->foreign('buyer_id')
        ->references('id')
        ->on('buyers')
        ->onDelete('cascade');
    });
}

我也不知道如何在我的刀片视图中显示它。

TrackerController.php

 public function index()
 {
   $trackers = Tracker::latest()->paginate(5);
   return view('trackers.index',compact('trackers'))
    ->with('i', (request()->input('page', 1) - 1) * 5);
  }

index.blade.php

      @foreach ($trackers as $tracker)
      <tr>
          <td>{{ ++$i }}</td>
          <td>{{ $tracker->style_name }}</td>
          <td>{{ $tracker->buyer_name }}</td>
      </tr>
       @endforeach

谢谢。

【问题讨论】:

    标签: laravel eloquent laravel-6


    【解决方案1】:

    您需要使用belongsTo 关系。买方是 Tracker 的父母。

    public function buyer()
        {
            return $this->belongsTo('App\Buyer','buyer_id');
        }
    

    在刀片中

    <td>{{ $tracker->buyer->buyer_name }}</td>
    

    阅读 laravel doc here 了解一对多反向关系。

    【讨论】:

    • 谢谢。我红了文档,但这对我来说太混乱了。努力学习。它现在正在工作。再次感谢。
    猜你喜欢
    • 2020-05-11
    • 2015-02-07
    • 2020-07-20
    • 2016-02-22
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多