我得到了一个未定义的错误属性:
Illuminate\Database\Eloquent\Relations\BelongsTo::$name
(视图: C:\xampp\htdocs\ESchool\resources\views\front\index.blade.php) )
我不知道是怎么回事
这是我的索引页面中获得错误<的部分。
div class="special_cource_text">
<a href="../../../../../../Users/Khaldoun%20Alhalabi/Desktop/etrain/course-details.html"
class="btn_4">{{$course->categories()->name}}</a>在这里我的分类模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $table = "categories" ;
protected $primaryKey = "id" ;
public $timestamps = true ;
protected $fillable =
[
'name' ,
] ;
/**
* Get all of the comments for the Category
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function courses()
{
return $this->hasMany(Course::class, 'foreign_key');
}
}在这里我的课程模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
use HasFactory;
protected $table = "courses" ;
protected $primaryKey = "id" ;
public $timestamps = true ;
protected $fillable =
[
'name' ,
'image' ,
'price' ,
'small_description' ,
'description' ,
] ;
public function categories()
{
return $this->belongsTo(Category::class);
}
public function trainers()
{
return $this->belongsTo(Trainer::class);
}
public function students()
{
return $this->belongsTo( Student::class );
}
}发布于 2022-03-28 11:06:30
我解决了,问题是以外键的名义命名为cat_id,但肯定是category_id在laravel https://laravel.com/docs/9.x/eloquent-relationships#one-to-many的文档中找到的。
发布于 2022-03-28 08:12:46
public function categories()改为public function category()(其他职能相同。BelongsTo返回一个对象,因此函数名应该是单数)
$course->category->name
https://stackoverflow.com/questions/71638626
复制相似问题