Jump to content

Laravel Multiple Relations

Go to solution Solved by Cruorzy,

Dont be so dumb as me, just scroll a bit further in the documentation

 

 

Stock.php

return $this->hasOne('App\Stat', 'id', 'store_id');

 

Fixed it.

 

Not sure how to explain this but let me give it a shot.

Keep in mind i want to achieve this in Laravel.

59412b799c356_miniERD.png.7c9428c055850f39d6fd7b3e85364b9e.png

 

What i've got now is the page that display the Item name. and a join to the Stock table so i can use anything in there related to the item too.

Can't seem quickly to figure out how i make sure that it makes nicely a join from the "store_id" to the Stores Table.

Trying to do this on a Laravel approved way :)

 

Code now.

 

 

web.php

Route::get('/item/{name}', 'ItemController@show');

 

 

ItemController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{
	public function show($name)
    {
		$item = Item::where('name', $name)->firstOrFail();
		return view('item.show')->with('item', $item);
	}
}

 

 

show.blade.php

{{$item->name}}

@foreach ($item->getStock as $shop)

	{{$shop->in_stock}}

@endforeach

 

Item.php (Model)

public function getItemStats()
	{
		return $this->hasMany('App\Stock');
	}

 

 

 

This works just fine but when i try to link "store_id" from the Stock table and the "id" from the Stores table.

Im not sure about how to do that properly.

 

What i thought...

 

 

Stock.php

public function getStat()
{
	return $this->hasOne('App\Stores');
}

 

 

show.blade.php

{{$item->name}}

@foreach ($item->getStock as $shop)

	<!-- I want here to list the shop name from the Stores table-->
	{{$shop->getStore->store_name}} <!-- Something like this-->

	{{$shop->in_stock}}

@endforeach

 

the thing is im getting a error page which makes sense, but im kind of stuck and wanted to make a quick post so i might fix this faster :)

ErrorException (1/2)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stores.item_store_id' in 'where clause'

ErrorException (2/2)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stores.item_store_id' in 'where clause' (SQL: select * from `stores` where `stores`.`item_store_id` is null and `stores`.`item_store_id` is not null limit 1)

Im sure there is a way to set the column he is looking for (item_store_id) to just (id)

But then he is looking for a value where NULL.

Quote or mention me if not feel ignored 

Link to comment
https://linustechtips.com/topic/793108-laravel-multiple-relations/
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×