I have three tables, stores, store_categories and product_categories. Structure of each table is below
stores
id name
1 Mystore
store_categories
id store_id product_category_id
1 1 1
2 1 2
product_categories
id name
1 Grocery
2 Vegetable
In my Store model, I write the relation
public function store_categories(){
return $this->hasMany('App\StoreCategory');
}
So to get all data of a store, I write i StoresController
$res = Store::with('store_categories')->get(); dump($res);
But the dump shows store_id and product_category_id in relations. How can I display their names( ie store name, product category name etc ) ?
You need to add Many to Many relationship as follows:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
/**
* The roles that belong to the user.
*/
public function categories()
{
return $this->belongsToMany('App\ProductCategory','store_categories','store_id','product_category_id');
}
}
Then you can perform the following:
$res = Store::with('categories')->get(); dump($res);
Related
I have three table country, state, customer_contacts. I want display all customer details into list view structure. But in my customer table only id save of country and state respectively. I want to fetch Country nad state Name from other two table .
Table structure as follows :
1. Country
id name
1 India
2 Canada
2. State
id name country_id
1 Mumbai 1
2 Delhi 1
3 abc 2
4 xyz 2
3. Customer_contact
id c_name country_id state_id
1 abcdee 1 2
2 xyzerr 1 1
3 extraa 2 3
4 newsss 2 4
i want to fetch customer name with country name and state name.
I am using below query to fetch data but getting only customer_contact data how to fetch name using any query or relationship.
$data = CustomerContact::with('Country', 'State')->get();
I am using relationship as follow:
1) Country Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public function state()
{
return $this->hasMany(State::class);
}
public function customercontact()
{
return $this->hasMany(CustomerContact::class);
}
}
2) State Model
class State extends Model
{
public function customercontact()
{
return $this->hasMany(CustomerContact::class);
}
public function country()
{
return $this->belongsTo(Country::class);
}
}
3) CustomerContact
use Illuminate\Database\Eloquent\Model;
class CustomerContact extends Model
{
protected $guarded = [];
public function country()
{
return $this->belongsTo(Country::class);
}
public function state()
{
return $this->belongsTo(State::class);
}
}
I want show data in list view like CustomerName, CountryName,StateName.
When i do
dd($data)
getting data with country and state id but relationship getting null value.
Help me in this.
On CustomerSupport you defined two function country() and state(), so your code will be :
$data = CustomerContact::with('country','state')->get();
Or,
$data = CustomerContact::with('country')->with('state')->get();
I need to create a relationship between user and many stores. I have created a three models
Store Model
id name email phone info
1 xyz xyz#gmail.com 9329292922 Small Store
2 abc abc#gmail.com 9494949449 Some Store
User Model
id name email
1 ewd ewd#gmail.com
2 xcv xcv#gmail.com
User_Store
user_id store_id
1 1
1 2
What does the user_store model contain relations whether it is belongstoMany or hasmany?
You can use belongsToMany relationship
In your Store model define a method
public function users() {
return $this->belongsToMany(Users::class, 'user_store', 'user_id', 'store_id');
}
In your Users model define a method
public function stores() {
return $this->belongsToMany(Stores::class, 'user_store', 'user_id', 'store_id');
}
Looks to me like you want a simple many-to-many relationship.
For this you only need two models User and Store, you only need StoreUser if you want to do something special with the pivot table otherwise it is unnecessary.
The following would be the Laravel way:
Table structure
stores
id
name
email
phone
info
users
id
name
email
store_user
user_id
store_id
Laravel excepts the pivot table to be called store_user, you can read more about it here:
To define this relationship, three database tables are needed: users,
roles, and role_user. The role_user table is derived from the
alphabetical order of the related model names, and contains the
user_id and role_id columns.
Model structure
class User extends Model
{
public function stores()
{
return $this->belongsToMany(Store::class);
}
}
class Store extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
Consider I have the following table structures for tables countries, products and suppliers:
countries
------------------------
id
name
code
product
------------------------
id
name
price
suppliers
------------------------
id
name
A product can be sold in different countries but supplier of that product can be different. With that keeping in mind, I made a relations table to keep track of which supplier is delivering which product in which country:
relations
------------------------
country_id
product_id
supplier_id
Let's say I have a product A which I need to store in country US and CA but the suppliers for these countries are X and Y respectively. The structure would look something like this:
countries
-------------------------------
id | name | code
-------------------------------
1 | United States | US
2 | Canada | CA
product
-------------------------------
id | name | price
-------------------------------
1 | A | 3.99
suppliers
------------
id | name
------------
1 | X
2 | Y
relations
-------------------------------
country_id | product_id | supplier_id
-------------------------------
1 | 1 | 1
2 | 1 | 2
My question is how can I use Eloquent Relationships to this table since many-to-many relationships only work on two tables. Is there any other workaround regarding this? Or is there any other efficient way to implement this scenario?
Thank you for your help.
There is no built-in way to make a relation using three tables. Whenever I encounter something like this myself, the best solution seems to be to make an in-between model that has relations to the three tables.
So in your case, I would create a SupplierProduct that has the relations country, supplier and product.
i have also same scenario class have multiple DaysClassDetails
use this function in your parent model
public function classType()
{
return $this->hasMany('App\DaysClassDetails(middlemodel)');
}
and DaysClassDetails have multiple DaysClassTimeDetails
public function classTime()
{
return $this->hasMany('App\DaysClassTimeDetails(lastchildmodel)');
}
public function classType(){
return $this->belongsTo('App\ManageClass(parentmodel)');
}
As Jerodev suggested, I made an intermediate model SupplierProduct. Instead of making many-to-many relationships, I made one-to-many relationships with SupplierProduct and retrieved data using with functions to retrieve all data related to that record.
This is how my Models look like (database structure is same as described in question):
SupplierProduct.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SupplierProduct extends Model {
public function country() {
return $this->belongsTo(Country::class);
}
public function product() {
return $this->belongsTo(Product::class);
}
public function supplier() {
return $this->belongsTo(Supplier::class);
}
}
Country.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
public function products() {
return $this->hasMany(SupplierProduct::class)->with('product', 'supplier');
}
}
Product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function products() {
return $this->hasMany(SupplierProduct::class)->with('country', 'supplier');
}
}
Supplier.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model {
public function products() {
return $this->hasMany(SupplierProduct::class)->with('country', 'product');
}
}
I am using User model to fetch user_type = 5. They are associated with user_type = 3 in vendors table. I want to make a relationship in User or Vendor model which could help me get users of type 5 along with the associated user of type 3.
To get data with a criteria you can use scopes, like this :
public function scopeMyType($query)
{
return $query->where('user_type ', 3);
}
To use it :
$users = User::myType()->get();
// this will return users with type = 3
You can make self relationship like this:
class User extends \Eloquent {
....
public function hasOne() {
$children = $this->hasMany('Vendor');
}
}
I have 3 tables
Users
-------------
user_id (PK)
user_name
Items_distributed
-------------
user_id (FK)
item_id(FK)
Item List
-----------------
item_id(PK)
item_name
Now i need to print Items_distributed table by taking both the user_id and item_id and dispaly their item_name and user_name
i dont know how to display both things at a time
if i display either item_name or user_name its working
but when i try to print both it is not working .
Can any one solve my problem .
This is how i print the values
in controller i use like this
$itemdata=item::orderBy('user_id','desc')->paginate(10);
and in view
i use
#foreach($itemdata as $value)
<tr>
<td>{{$value->items->item_name}}</td>
<td>{{$value->users->user_name}}</td>
<td>{!!Html::link("editItem/",'Edit',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}
{!!Html::link("deleteItem/".$value->item_id,'Delete',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}</td>
</tr>
#endforeach
You should use Laravel Eloquent Relationship. When you create model file for DB Table, You just put relation with other model.
If Relation has set, than Laravel it self fetch data from Related table.
In your case, Three models are created.
1) User Model.
2) Item Model.
3) ItemDestributed Model.
UserModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Items extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemDestributionModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemDestribution extends Model
{
/**
* Other code goes here
**/
public function user()
{
return $this->belongsTo('App\User','foreign_key_of_user');
}
public function item()
{
return $this->belongsTo('App\Item','foreign_key_of_item');
}
}
You can find more about Eloquent Relation from Here.