简体   繁体   中英

One to Many Relationship - Laravel & Mysql

In my application, Users can have many products. Now, i am trying to display the users phone number for a every displayed products.

In my products table, there is a column user_id for the respective users.
This is how my model looks like

User Model

public function products()
{
      return $this->belongsTo('Models\Database\User','user_id');    
} 

Product Model

class Product extends BaseModel {

protected $fillable = ['user_id','type', 'name', 'slug', 'sku', 'description',
    'status', 'in_stock', 'track_stock', 'qty', 'is_taxable', 'page_title', 'page_description'];

 // protected $guarded = ['id'];

public static function getCollection()
{
    $model = new static;
    $products = $model->all();
    $productCollection = new ProductCollection();
    $productCollection->setCollection($products);
    return $productCollection;
}

public function users()
{
    return $this->hasMany('\Models\Database\Product');
    //->withTimestamps();
}



public function categories()
{
    return $this->belongsToMany(Category::class);
}

public function reviews()
{
    return $this->hasMany(Review::class);
}

public function prices()
{
    return $this->hasMany(ProductPrice::class);
}









public function orders()
{
    return $this->hasMany(Order::class);
}

public function users()
{
      return $this->hasMany('Models\Database\Product');
}

And in my view, this is how i try to get the respective user's phone number

<p>{{$product->users->phone}}</p>

But i get an error like

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.product_id' in 'where clause' (SQL: select * from products where products . product_id = 1 and products . product_id is not null)

You should do:

User Model

public function products()
{
      return $this->hasMany('Models\Database\Product');    
} 

Product Model

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

In your blade:

{{ $product->user->phone }}

You have got your relationship models inverted,

change them:

In your User model:

public function products()
{
      return $this->hasMany('Models\Database\Product');
} 

In your Product model:

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

And then you could access the properties like:

<p>{{$product->user->phone}}</p>

Link to the Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM