简体   繁体   English

一对多关系-Laravel和Mysql

[英]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. 在我的产品表中,相应用户有一个列user_id
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 { 类Product扩展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) SQLSTATE [42S22]:柱未找到:1054未知列在'where子句' 'products.product_id'(SQL:SELECT * FROM products ,其中productsproduct_id = 1和productsproduct_id不为空)

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 链接到文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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