0
votes

I have a hasOne(Many) relation function like this:

return $this->hasOne('App\Models\ProductTranslation','product_id','id')->where('language_id', $language_id['id']);

Also, I tried to use

return $this->hasOne('App\Models\ProductTranslation','product_id','id')->select('product_translations.name')->where('language_id', '1');

In Controller use this

$value=Product::with('translation:name')->find(1);

I try to receive only one specific column from the table, but it returned an empty array. In debug bar I see the query when I use it in PHPMyAdmin it return only one column as I want.

Is this possible?

P.S (use Laravel 5.8.34)

Updating

I choose 'Entity Layers for Translated Fields and Non-Translated Fields' approach for translation in the project and have a database like this Database picture

1
select() must always contains the foreign key column.Tharaka Dilshan
Resolve by you comment @TharakaDilshan $value=Product::with('translation:name,**product_id**')->find(1);Hik200

1 Answers

1
votes

If you want to get only that language_id type of translation then you might do like this.

$language_id = 1;
$products = Product::with(array('translation'=>function($query) use($language_id){
    $query->where('language_id',$language_id);
}))->get();

and if you want to select name then like this make sure you've to select id,name id is a must.

$language_id = 1;
$products = Product::with(array('translation'=>function($query) use($language_id){
    $query->where('language_id',$language_id)->select('id','name');
}))->get();

Remove where conditions from models.

As per your DB structure in Language it's belongsToMany with role

Languages.php model

public function role(){
    returh $this->belongsToMany('App\Models\Role','role_translations','language_id','role_id')
}

$language_id = 1;
$products = Product::with(array('translation.role'=>function($query) use($language_id){
    $query->where('role_translations.language_id',$language_id)->select('languages.id','languages.name');
}))->get();