Hi im pretty new to laravel so hope you dont mind for my lack of knowledge. here is my code
ive created a table pizza_prices with foreignId which reference on pizzas table on the column pizza_id.
Schema::create('pizza_prices', function (Blueprint $table) {
$table->id();
$table->string('small')->default(4);
$table->string('medium')->default(4);
$table->string('large')->default(4);
$table->foreignId('pizza_id')
->constrained('pizzas', 'pizza_id')
->cascadeOnDelete();
$table->timestamps();
});
on the PizzaPrice model
public function pizza(): BelongsTo
{
return $this->belongsTo(Pizza::class, 'pizza_id');
}
Schema::create('pizzas', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('ingredients');
$table->unsignedBigInteger('pizza_id')->unique();
$table->timestamps();
});
on the Pizza model
public function pizzaPrice(): HasOne
{
return $this->hasOne(PizzaPrice::class);
}
on the pizzas table
'id' => 1,
'name' => 'supreme',
'ingredients' => 'salami',
'pizza_id' = 59
on the pizza_prices table
'id' => 1,
'small' => 6,
'medium' => 9,
'large' => 19,
'pizza_id' => 59
now to my problem
$pizza = Pizza::find(1); // give me the correct data
'id' => 1,
'name' => 'supreme',
'ingredients' => 'salami',
'pizza_id' = 59
dd($pizza->pizzaPrice)
output
null // app/Http/Controllers/UserController.php:16
i expect the output to give me this
'id' => 1,
'small' => 6,
'medium' => 9,
'large' => 19,
'pizza_id' => 59
but well i dont know what mistake did i make. hope you guys can help me out.
Edit: https://stackoverflow.com/questions/68049360/laravel-eloquent-relationship-returning-null problem solve xD
Hello @spawn2k,
As also mentioned in the stack overflow post you need to explicitly define your local and foreign key in both the relationships because you are not using the default id
column for referencing.
So, your relationships should be defined as:
on the PizzaPrice model
public function pizza(): BelongsTo
{
return $this->belongsTo(Pizza::class, 'pizza_id','pizza_id');
}
on the pizzas model
public function pizzaPrice(): HasOne
{
return $this->hasOne(PizzaPrice::class, 'pizza_id','pizza_id');
}
Thanks
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community