dou91855 2014-11-30 01:34
浏览 78
已采纳

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 01: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部