简体   繁体   English

如果不存在关系,Laravel会获得具有默认值的雄辩关系?

[英]Laravel get Eloquent relation with default value if relation is not present?

I have a Post model , each post has many translations for example : ru , fr , en - ( post_translations table), The working code for getting all posts with a specific translations is like this (eg fr ): 我有一个Post模型中,每个岗位都有例如许多翻译: rufren - ( post_translations表),用于获取所有文章与特定的翻译工作代码是这样的(如fr ):

 $locale = 'fr';
 $posts = Post::with([
        'translations' => function($q) use($locale){
            $q->where('language', $locale);
        }
    ])->get();

But some of $posts does not have fr translation, all posts have en translation . 但是$posts中的一些没有fr翻译,所有posts都有en translation。

I want to get all posts with fr translation and for posts which does not have fr , return en translation! 我想获取所有带有fr翻译的帖子,而对于没有fr帖子,请返回en translation!

Do I have to do this manually? 我是否必须手动执行此操作? ei loop trough all posts and add en translation to those which does not have fr or there is a laravel way to do this ? ei遍历所有帖子并在没有fr或laravel方式的帖子上添加en翻译。

Try this solution to get all fr: 尝试此解决方案以获取所有fr:

$posts = Post::whereHas('translations', function($q) use($locale){
    $q->where('language', $locale);
})->get();

Hope it help :) 希望对您有所帮助:)

From what you write, I understand that Posts are always written in English and then translated in other languages. 从您写的内容来看,我知道帖子总是用英语撰写,然后再翻译成其他语言。

I do not know the use you have to do about this, but I propose you to query all the posts with French and English translations and then filter them while printing them 我不知道您有什么用,但是我建议您使用法语和英语翻译查询所有帖子,然后在打印时过滤它们

$locale = 'fr';
$posts = Post::with([
    'translations' => function($q) use($locale){
        $q->where('language', $locale);
        $q->orWhere('language', 'en');
    }
])->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM