【发布时间】: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
【问题讨论】:
-
您的代码似乎是正确的。该错误表明某些
player没有country。只需检查您的数据库记录。
标签: laravel model-view-controller