我正在构建一个大学项目,我无法传递具有主表/类的第二个表中的数据。
当我尝试传递它并在视图中访问它时,我收到尝试访问非对象错误。
这是我下面的代码。
体育课
class Gym extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
*/
protected $table = 'gyms';
public $gym;
public function reviews()
{
return $this->hasMany('Review', 'unique_gym_id'); // represents the Review class
}
页面控制器相关部分,我将数据从此循环传递到视图。
foreach($gymsearchs as $gymsearch)
{
Gym::save($gymsearch);
$gyms[] = DB::table('gyms')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
Review::review($gymsearch);
$reviews[] = DB::table('reviews')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
}
//dd($reviews); this shows the full review object contents fine
$data = array_add($data, 'gyms', $gyms, 'reviews', $reviews);
视图
@foreach(array_slice($gyms, 0, 5) as $gym)
{{$gym->name}} // works fine and with other objects from the $gym
@endforeach
@foreach(array_slice($gyms, 0, 5) as $gym)
{{$gym->review}} // this gives me a trying to access non object error.
@endforeach
健身房模型和评论模型都unique_gym_id为一列
我以为健身房模型中的这个复习课应该用$gym来研究复习表数据吗?
public function reviews()
{
return $this->hasMany('Review', 'place_id');
}
知道我错过了什么吗? 谢谢我是Laravel和PHP的新手
你告诉它是一个hasMany关系,所以不应该是"{{$gym->reviews}}"吗?没有尝试过,但似乎很奇怪。此外,这应该返回一个数组而不是单个对象,因此您必须迭代它。
编辑:
这整个部分:
foreach($gymsearchs as $gymsearch)
{
Gym::save($gymsearch);
$gyms[] = DB::table('gyms')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
Review::review($gymsearch);
$reviews[] = DB::table('reviews')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
}
//dd($reviews); this shows the full review object contents fine
$data = array_add($data, 'gyms', $gyms, 'reviews', $reviews);
可能是
Gym::save($gymsearchs);
$gyms = Gym::where('unique_gym_id', 'in', array_map(create_function('$o', 'return $o->unique_gym_id;'), $gymsearchs))->get();
$data['gyms'] = $gyms;
,因为您似乎不使用$reviews。但我不太明白健身房搜索的意图以及你想用 Review::review($gymsearch) 方法做什么。此外,您还应该研究这种情况的急切加载。有一个 ->with($relation) 函数,可以急切加载您的所有评论。通过这种方式,您可以优化发送到数据库的查询数量。