【发布时间】:2021-05-13 11:24:06
【问题描述】:
我目前正在尝试为我的 laravel 应用程序添加一个最喜欢的功能。我正在尝试用 eloquent 访问 post 表,但它说属性 posts(最喜欢的模型中的函数)不存在。
更新:我更新了查询。如果我转储 $favorite,我会得到两个项目,这是正确的,但现在我收到此错误消息:Property [posts] 在 Eloquent 构建器实例上不存在。 (查看:C:\xampp\laravelprojects\Skakahand\resources\views\profile\index.blade.php)
<div class="favorite-section">
<p>Mina favoriter</p>
{{$favorite->posts->title}}
</div>
这是我的控制器:
public function index(User $user)
{
$favorite = Favorite::where('user_id', auth()->user()->id)
->get();
return view('profile.index',[
'user' => $user,
'favorite' => $favorite
]);
}
最喜欢的型号:
class Favorite extends Model
{
use HasFactory;
protected $fillable = [
'user_id'
];
public function users()
{
return $this->belongsTo(User::class);
}
public function posts()
{
return $this->belongsTo(Post::class);
}
}
并发布模型:
class Post extends Model
{
use HasFactory;
/* use Sluggable; */
protected $fillable = [
'title',
'body',
'category',
'decision',
'number',
'place',
'image_path',
'slug',
'price',
'user_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function favorites(){
return $this->hasMany(Favorite::class);
}
}
【问题讨论】:
-
转储
$favorite会得到什么? -
Illuminate\Database\Eloquent\Collection {#620 ▼ #items: [] }
-
基本没有
-
我将查询更改为 $favorite = Favorite::where('user_id', auth()->user()->id) 现在我得到两个项目,但仍然出现此错误消息 Property [posts ] 在 Eloquent 构建器实例上不存在。 (查看:C:\xampp\laravelprojects\Skakahand\resources\views\profile\index.blade.php)
标签: laravel