[英]One to Many Relationship - Laravel & Mysql
在我的應用程序中,用戶可以擁有許多產品。 現在,我試圖顯示每個顯示產品的用戶電話號碼。
在我的產品表中,相應用戶有一個列user_id
。
這就是我的模型的樣子
用戶模型
public function products()
{
return $this->belongsTo('Models\Database\User','user_id');
}
產品型號
類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');
}
在我看來,這就是我嘗試獲取相應用戶的電話號碼的方式
<p>{{$product->users->phone}}</p>
但是我得到一個錯誤
SQLSTATE [42S22]:柱未找到:1054未知列在'where子句' 'products.product_id'(SQL:SELECT * FROM
products
,其中products
。product_id
= 1和products
。product_id
不為空)
你應該做:
用戶模型
public function products()
{
return $this->hasMany('Models\Database\Product');
}
產品型號
public function user()
{
return $this->belongsTo('Models\Database\User');
}
在刀片中:
{{ $product->user->phone }}
您已經顛倒了關系模型,
更改它們:
在您的用戶模型中:
public function products()
{
return $this->hasMany('Models\Database\Product');
}
在您的產品模型中:
public function user()
{
return $this->belongsTo('Models\Database\User','user_id');
}
然后您可以訪問以下屬性:
<p>{{$product->user->phone}}</p>
鏈接到文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.