【问题标题】:Laravel Models and displaying them on view togetherLaravel 模型并将它们一起显示在视图中
【发布时间】:2019-10-05 13:10:28
【问题描述】:

对于学校作业,我们有两个表格和模型玩家和国家 我知道它要么是我的模型,要么是我的控制器(我之前遇到过这个问题,但在另一项任务中,他们只是一个国家,所以我只是遍历了一个国家变量并使用了数组,但这不适用于多个国家)
当我尝试在视图中显示时,我得到“尝试在 {{$player->country->name}} 上获取非对象“名称”的属性,这是老师明确表示我们要显示的方式它。

目前,在其他任何事情之前,我都喜欢显示我所有的球员和他们的国家/地区名称
模型

class Country extends Model
{
    //
    protected $table = 'countries';
    protected $fillable=['name','flag'];
    public function player(){
        return $this->hasMany(Player::class);
    }
}


class Player extends Model
{
    //
    protected $fillable =['name','age','role','batting','bowling','image','odiRuns','countries_id'];
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}


表格

public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('flag');
            $table->timestamps();
        });
    }


public function up()
    {
        Schema::create('players', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('age');
            $table->string('role');
            $table->string('batting');
            $table->string('bowling');
            $table->string('image');
            $table->string('odiRuns');
            $table->integer('countries_id')->unsigned();
            $table->foreign('countries_id')->references('id')->on('countries');
            $table->timestamps();
         });
    }

控制器

use App\Player;
use App\Country;
use Illuminate\Http\Request;

class PlayerController extends Controller
{
 public function index()
    {
        //
        $players=Player::all();

        return view('index',compact('players'));
    }


查看

@extends('layout')
@section('content')

    @foreach ($players as $player )
    {{$player->name}}
    {{$player->age}}
    {{$player->role}}
    {{$player->batting}}
    {{$player->bowling}}
    {{$player->odiRuns}}
    {{$player->country->name}}
    @endforeach
    @endsection

编辑 玩家都有与国家表相关的国家 ID 表格 players table

countries table

【问题讨论】:

  • 您的代码似乎是正确的。该错误表明某些player 没有country。只需检查您的数据库记录。

标签: laravel model-view-controller


【解决方案1】:

问题是您缺少相关的外键。当你定义一个关系时,如果你明确地不告诉该关系使用哪个外键,Laravel 会寻找一个像 relationname_primarykeyoftheparenttable 这样的外键。在您的情况下,它是country_id,但在您的玩家表中,列名是countries_id。所以关系没有建立,你会出错。更改列名或告诉关系使用哪个外键来建立关系。

class Player extends Model
{
    protected $fillable =['name','age','role','batting','bowling','image','odiRuns','countries_id'];

    public function country()
    {
        return $this->belongsTo(Country::class,'countries_id');
    }
}

Laravel Doc

【讨论】:

  • 谢谢你,我在一秒钟前没有意识到这一点,以及 laravel 如何查找外键。非常感谢您对此背后的洞察力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
相关资源
最近更新 更多