【发布时间】:2023-03-26 19:05:01
【问题描述】:
我正在尝试通过 id 从另一个表中获取列,但每当我在视图中使用 foreach 时都会收到此错误
此集合实例上不存在属性 [id]。 (查看:C:\xampp\htdocs\myUniMentor\resources\views\userProfile\viewUserProfilePage.blade.php)
但是,如果我在没有 foreach 类似 $users->reviews 的命令的情况下运行代码,我会得到 review 表的数组以及与该特定 ID 相关的所有内容,并且这样做 $users->reviews->comments 会给我一个错误
此集合实例上不存在属性 [cmets]。 (查看:C:\xampp\htdocs\myUniMentor\resources\views\userProfile\viewUserProfilePage.blade.php)
我的问题是:
- 如何使用模型显示 cmets?
-
$users->reviews如何只返回与 id 关联的列?是不是因为我在belongsTo()中传递了id?
ReviewController.php
public function showUserProfile($id) {
$users = User::find($id);
// echo $users->first_name;
return view('userProfile.viewUserProfilePage', compact('users'));
}
}
public function addNewReview($id) {
$stars = Input::get("rating");
$message = Input::get("message");
// $users = User::find($id);
$users = User::where('id', $id)->first();
// echo $stars;
// echo $message;
// echo $users;
// echo $users->id;
// echo Auth::user()->id;
// die();
$reviews = new Review();
$reviews->user_id = $users->id;
$reviews->given_by = Auth::user()->first_name . ' ' . Auth::user()->last_name;
$reviews->stars = $stars;
$reviews->comments = $message;
$reviews->save();
Session::flash('message','Your Review has been added to the Mentor');
return redirect('show-user-profile/' . $users->id);
}
show-user-profile.blade.php
@section('content2')
<h3>Reviews</h3>
<p>{{ $users->reviews->comments }}</p>
@endsection
Review.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Review extends Model
{
protected $fillable = [
'comments', 'stars', 'given_by',
];
public function users()
{
return $this->belongsTo('App\User', 'user_id','id');
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\UserType;
use App\Subject;
use App\SubjectKeyword;
use App\Review;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'type', 'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getAllUsers() {
return User::all();
}
public function userTypes()
{
return $this->belongsTo('App\Users');
}
// public function subjects()
// {
// return $this->belongsToMany('App\Subject');
// }
public function subjects(){
return $this->belongsTo('App\Subject','subject_id','id');
}
public function reviews(){
return $this->hasMany('App\Review');
}
public function subjectKeywords(){
return $this->hasMany('App\SubjectKeyword');
}
}
【问题讨论】:
标签: laravel model-view-controller eloquent eloquent-relationship