简体   繁体   中英

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 ):

 $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 .

I want to get all posts with fr translation and for posts which does not have fr , return 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 ?

Try this solution to get all 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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