与Laravel的嵌套关系5.4 Eloquent

时间:2017-05-17 20:56:07

标签: php laravel eloquent relationships

我是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);

但我不认为那是最好的解决方案。希望你们中的任何人都有一些见解!

1 个答案:

答案 0 :(得分:1)

您最期待的是:

df <- data.frame(degree=rnorm(20), density=seq(0.01, 0.20, .01))

#only .05, .08, and .09 generate output
for (d in c(.05, .06, .07, .08, .09, .10)) { print(subset(df, density==d)) }

#this works as expected
for (d in seq(.01, .20, .01)) { print(subset(df, density==d)) }

#here is some evidence that machine precision may be to blame
diff(diff(seq(0.01, 0.20, .01)))

有关更多信息,请参阅: