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/