php - 为我的属性表创建照片模型

标签 php laravel

1)我有我的属性(property)模型

public function images()
{
     return $this->hasMany(PropertyImages::class);
}

2)我的PropertyImages模型表如下:

Schema::create('property_images', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('title')->nullable();
       $table->string('src');
       $table->string('mime_type')->nullable();
       $table->string('alt')->nullable();
       $table->text('description')->nullable();
       $table->integer('property_id');
       $table->timestamps();
});

3)当我有代码时:

$properties = Property::all();
dd($properties->images());

似乎没有什么效果。 我想要它,这样每个属性都有各种图像我想知道为什么它不识别数据。我收到以下错误:BadMethodCallException 方法 Illuminate\Database\Eloquent\Collection::images 不存在。

最佳答案

您正在尝试调用集合中的对象函数。要获取图像,您需要迭代 Collection。试试这个:

$properties = Property::all();
foreach ($properties as $property) {
    dd($property->images);
}

或者甚至尝试一次只获取一个对象:

$property = Property::first();
dd($property->images);

您必须注意的另一个细节是,您通常不会像函数一样调用关系,而是像属性一样调用它。因此,不要调用 $obj->images(),而是调用 $obj->images

关于php - 为我的属性表创建照片模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58650982/

相关文章:

laravel - http ://localhost:8000/broadcasting/auth 404 (Not Found)

PHP Laravel 按周从数据库获取数据

php - 图片后面出现下拉菜单

javascript - 如何在我的vue js中实现无限滚动

php - 如果记录存在则 Laravel 更新或如果不存在则创建

laravel - 在 Laravel 中使用 Eloquent 查询连接表

php - 如何在已部署的网站中创建符号链接(symbolic link)

javascript - 无法评估 AJAX 调用的 true/false 返回

php - 如何将 MongoDB find() 的所有结果输出到 jQuery html() 中?

PHP 函数创建长度递增的字符串 block ("fd6eg3"=> "f", "fd", "fd6", "fd6eg3")