0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hik200
  • 107
  • 11

1 Answers1

1

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();
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
  • this solution don;t work for me Model `return $this->hasMany('App\Models\ProductTranslation','product_id','id');` Controller `$language_id = 1; $products = Product::with(array('translation'=>function($query) use($language_id){ $query->where('language_id',$language_id)->select('id','name'); }))->get();` I choose 'Entity Layers for Translated Fields and Non-Translated Fields' for translation in the project and have a database like this [Database picture](https://imgur.com/a/OClUozi) – Hik200 Sep 16 '19 at 11:50
  • Yeah by comment understand that in select must be a foreign key column – Hik200 Sep 17 '19 at 07:56
  • Have you got your solution? – Dilip Hirapara Sep 17 '19 at 08:07
  • 1
    Yeah, your answer very good, in future think what I will use. – Hik200 Sep 18 '19 at 08:42