douxu4610 2016-10-29 18:47
浏览 54
已采纳

尝试使用模型关系获取非对象的属性

I'm trying to get a relationship between models in a laravel template. I want to get the product fields respective to an ad.

This is my AdController:

public function ads(Request $request)
    {
        $this->adRepository->pushCriteria(new RequestCriteria($request));     
        $hash = Auth::user()->environment_hash;
        $ads = $this->adRepository->findByHash($hash);
        return view('ads.index')
            ->with('ads', $ads);
    }

This how I'm parsing to my blade template:

@foreach($ads as $ad)
            <tr>
                <td>{!! $ad->product->name !!}</td>
            </tr>
@endforeach

But I keep getting this error:

Trying to get property of non-object

This is the adRepository file:

public function findByHash($hash = null)
    {
        $model = $this->model;

        if($hash)
            $this->model->where('environment_hash',  $hash);
        else
            $this->model->where('environment_hash',  Auth::user()->environment_hash);

        return $model;
    }

This my Ad Model: Ad.php

<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Ad extends Model
{

    public function product()
    {
        return $this->belongsTo(Product::class);
    }
}

This is my ad table:

id
product_id
environment_hash

And my product table:

id
environment_hash
name

What is wrong with the code?

  • 写回答

1条回答 默认 最新

  • dongzhuo1930 2016-10-29 18:54
    关注

    Not sure but there must be some ad which has no product in your database. So this may be the reason you are getting error. Make sure that all of your ad has related product in database.

    You can test it by running following code:

     @foreach($ads as $ad) <tr> <td>Test  {!! $ad->product !!}</td> </tr> @endforeach
    

    If you get result like this:

      Test some_name
      Test
      Test some_another_name
    

    Then this is confirm that some ad has no related product.

    If this is the case then you need to if() check before accessing the attributes of product.

    Update

    The problem is that you are missing get() in your findByHash(). It should be as:

    public function findByHash($hash = null)
    {
        $model = $this->model;
    
        if($hash)
            $this->model->where('environment_hash',  $hash);
        else
            $this->model->where('environment_hash',  Auth::user()->environment_hash);
    
        return $model->get();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题