Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从hasMany/BELONGS获取数据,以建立有效的关系_Php_Laravel_Web_Eloquent - Fatal编程技术网

Php 从hasMany/BELONGS获取数据,以建立有效的关系

Php 从hasMany/BELONGS获取数据,以建立有效的关系,php,laravel,web,eloquent,Php,Laravel,Web,Eloquent,我有两个模型产品和图像,其中产品可以有一个或多个图像,图像有一个相关的产品,这些是我的模型 产品型号 产品型号中的: public function image() { return $this->hasOne(Image::class, 'pro_id'); } 在图像模型中: public function product() { return $this->belongsTo(product::class, 'pro_id'); } 在控制器中: $img =

我有两个模型产品和图像,其中产品可以有一个或多个图像,图像有一个相关的产品,这些是我的模型

产品型号

产品型号中的

public function image()
{
   return $this->hasOne(Image::class, 'pro_id');
}
在图像模型中:

public function product()
{
    return $this->belongsTo(product::class, 'pro_id');
}
在控制器中:

$img = product::find($id)->image->filename;

确保图像表中有该产品的记录。否则,您必须管理错误。

如何调用关系?发布你的控制器code@Espresso我编辑了购买后添加控制器,我想存储数据a将如何使用api请求发送数据可能您的产品没有图像,您是否获得空图像?我管理了,我想添加一个产品如何?我在这方面失败了,docs并没有真正帮助我如果查询到表中不存在的记录,它将返回一个错误(尝试从非对象获取属性)。向产品添加图像或使用
is\u null()
方法管理图像缺失。(
为空(product::find($id)->image)