Eloquent 中的空白 object belongsTo()

Blank object in Eloquent belongsTo()

我正在尝试显示 Item 的哪一个属性 (code)。 ServiceItem 将 Item 作为外键。但是我根本拿不到物品。

这个在blade模板中给出了一个空白object:

@foreach ($service->serviceItems as $serviceItem )
    {{ json_encode($serviceItem->item()) }}
@endforeach

这是我的模型声明:

//ServiceItem model
class ServiceItem extends Model
{
    use HasFactory;
    public $fillable = ['service_id', 'item_id', 'values'];

    public function service()
    {
        return $this->belongsTo(Service::class, 'foreign_key');
    }

    // this doesn't work
    public function item()
    {
        return $this->belongsTo(Item::class, 'foreign_key');
    }
}

// Service model
class Service extends Model
{
    use HasFactory;
    public $fillable = ['user_id', 'site_id', 'title', 'status', 'remarks', 'report', 'date'];

    public function user()
    {
        return $this->belongsTo('\App\Models\User');
    }

    public function site()
    {
        return $this->belongsTo('\App\Models\Site');
    }

    public function serviceItems() {
        return $this->hasMany('\App\Models\ServiceItem');
    }

}

这是我的控制器:

public function index()
{
    $services = Service::latest()->paginate(5);
    return view('services.index', compact('services'))
        ->with('i', (request()->input('page', 1) - 1) * 5);
}

请帮我在服务项目中显示 code 属性!!!非常感谢!

我想您阅读了模型关系定义的 Laravel 文档。他们提到将外键作为第二个参数,而不是 foreign_key 作为单词,而是引用父 table 的实际外键。您必须更改型号代码。

class ServiceItem extends Model
{
    use HasFactory;
    public $fillable = ['service_id', 'item_id', 'values'];

    public function service()
    {
        return $this->belongsTo(Service::class, 'service_id');
    }

    public function item()
    {
        return $this->belongsTo(Item::class, 'item_id');
    }
}

然后 $serviceItem->item 应该会按预期工作。