【发布时间】:2017-10-17 11:51:37
【问题描述】:
我是 Laravel 和 Eloquent 的新手。我已经建立了一些直接的项目,这很好。
现在我正在尝试构建一个更复杂的平台,但我真的被困在关系上。
也许方法是错误的,如果是这样的话,我当然想听听。思路如下:
我想拥有可以链接到多个渠道的产品。每个产品渠道组合都需要不同的帐户。 每个产品都与一个主要类别相关联,并且对于每个类别-渠道组合,它需要不同的参数。
我制作了以下表格:
channels
id
channel_name
accounts
id
user_id
channel_id
account_name
categories
id
category_name
products
id
user_id
category_id
product_name
channel_product
channel_id
product_id
account_id
pivot_data
category_channel
channel_id
category_id
目前我有以下型号:
class Channel extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)->withPivot(['pivot_data','account_id']);
}
}
class Product extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function account()
{
return ????;
}
}
class Category extends Model
{
public function channel()
{
return ????;
}
}
还有如下代码:
// Get channel
$channel = Channel::find(1);
// Get products for channel
$products = $channel->products;
// Walk through products
foreach ( $products as $product )
{
// OK
echo $product->product_name;
echo $product->user->user_name;
echo $product->category->category_name;
echo $product->pivot->pivot_data;
// NOT OK
echo $product->account; // NOT OK
echo $product->category->channel; // NOT OK
}
我不敢相信我正在尝试实现不可能。
当然可以: $account = Account::get($product->pivot->account_id);
但我认为这不是最好的解决方案。希望大家有一些见解!
【问题讨论】:
标签: php laravel eloquent relationships