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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?