【问题标题】:Laravel Model relationsLaravel 模型关系
【发布时间】:2019-04-04 14:29:57
【问题描述】:

我无法连接到 laravel 5.6

中的模型函数
     <img src="{{$item->file_id ? $item->photo->file_url() : 
    "http://www.ecmsnews.com/wp-content/themes/nucleare-pro/images/no-image-box.png"}}"  
     width="200" height="100">

这里我调用 $item file_id 来查找图片

public function photo(){
       return $this->belongsTo('App\Models\CRM_STAFF\Staff_files', 'file_id');
  }

我在模型中连接到其他模型以使用此功能

 public function file_url(){
        return ($this->_domain).($this->id);
}

但我得到这样的错误 enter image description here

【问题讨论】:

  • 在照片模型中声明了 file_url() 吗?如果不是,它在哪里声明?
  • 挂接调试器,找到返回错误的$item,验证文件id是否存在于代表Staff_files的表中。您可能需要对 FK 进行更好的参照完整性检查。
  • 检查关系是否存在而不是file_id是否存在不是更好吗?即$item-&gt;photo ? $item-&gt;photo-&gt;file_url() : "http://www.ecmsnews.com/wp-content/themes/nucleare-pro/images/no-image-box.png"
  • @SteveNosse $item->photo->file_url() is $item->model->model
  • @Devon $item->file_id 有 [932]

标签: php laravel


【解决方案1】:

在模型中添加with('photo') 以加载关系。然后检查$item-&gt;photo 是否不为空

$item = Item::with('photo')->where(...)->get();
return view('yourview', compact('item'));

然后在视图中

<img src="{{!is_null($item->photo) ? $item->photo->file_url() : "http://www.ecmsnews.com/wp-content/themes/nucleare-pro/images/no-image-box.png"}}" width="200" height="100">

【讨论】:

  • 急切加载是可选的,将它与 first() 结合使用是非常不必要的。
  • 感谢先生的建议,但我认为您误解了我检查 null 但该字段不为 null 的问题,我认为我无法将 2 个模型相互连接
【解决方案2】:

感谢所有愿意提供帮助的人 我找到了答案 问题是我用 Json_encode 保存所有文件,我只需要解码它

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2018-07-11
    • 2016-11-01
    • 2017-10-25
    • 2016-03-21
    • 2020-03-07
    • 2016-02-26
    相关资源
    最近更新 更多