【问题标题】:Nested relations with Laravel 5.4 Eloquent与 Laravel 5.4 Eloquent 的嵌套关系
【发布时间】: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


    【解决方案1】:

    您最有可能寻找的是:

    class Product extends Model
    {
        // ...
    
        public function account()
        {
            return $this->hasManyThrough(Account::class, Channel::class);
        }
    }
    
    class Category extends Model
    {
        public function channel()
        {
            return $this->belongsToMany(Channel::class);
        }
    }
    

    如需了解更多信息,请参阅:

    【讨论】:

    • 按照您的描述将帐户关系添加到 Product 模型时,我最终得到: Column not found: 1054 Unknown column 'channels.product_id' in 'field list' (SQL: select accounts .*, channels.product_id 来自accounts 内部连接channe ls channels.id = accounts.channel_id 其中channels.product_id =这是调用它的时候:$product->account
    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多