dou91855 2014-11-30 09:34
浏览 77
已采纳

Laravel Eloquent无法得到简单的hasMany关系工作

Background

I have an internationalized DB that stores its strings for different languages like this:

products
    id
    price

product_translation
    id
    product_id
    language_id
    name
    description

languages
    id
    name (e.g. 'English', 'German')
    code (e.g. 'en', 'de')

With appropriate Models for each table (Product, ProductTranslation, Language). In my views I want to fetch a list of products like this:

// get first 20 products, list name and price.
@foreach(Product::take(20)->get() as $product)
{{$product->translations->name}} {{$product->price}}
@endforeach

Problem

My app will return product names according to what the current App::getLocale() is set to (i.e. en and de).

I'm just starting out with Laravel's Eloquent, I'm unsure how to specify the correct relationships (or if I'm actually doing it correctly at all).

My attempt

I have specified a OneToMany relationship in between Product and ProductTranslation:

class Product extends \Eloquent {

    protected $with = ['translations'];

    public function translations()
    {
        return $this->hasMany('ProductTranslation');
    }
}

This works fine but will return all the translations (we only want the current locale).

I then specify a OneToOne relationship between ProductTranslation and Language:

class ProductTranslation extends \Eloquent {

    protected $with = ['language'];

    public function language()
    {
        return $this->hasOne('Language')
        ->where('code', App::getLocale());
    }
}

I know this doesn't work and I am stumped at what to do next. Does anyone have a cleaner approach?

  • 写回答

2条回答 默认 最新

  • du512926 2014-11-30 09:50
    关注
    class ProductTranslation extends \Eloquent {
    
        protected $with = ['language'];
    
        public function language()
        {
            return $this->hasOne('Language');
        }
    }
    

    In route or controller

    ProductTranslation::language()->where('code', '=', App::getLocale())->get();
    

    To keep this in the model do this

    public static function getLocale() 
    {
        return static::language()->where('code', '=', App::getLocale())->get();;
    }
    

    Call the function using ProductTranslation::getLocale()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘