Laravel 5.3 Eloquent Relationships

懵懂的女人 提交于 2019-12-25 08:50:15

问题


i'm using Laravel 5.3

and i'm trying to select from the database the values for the lang files,

i created a file and named it global.php

and inside the file i tried to do this:

use App\Dictionary;

$language_id = 1;

$dictionary = array();
$lables     = Dictionary::where('language_id',$language_id)->get();
foreach($lables as $label):
    $dictionary[$label->label] = $label->value;
endforeach;

return $dictionary;

now, this is working but i want to select the rows using the short_name field and not the id of the language

i want it to be something like this:

$lables     = Dictionary::all()->language()->where('short_name', 'en')->get();

my database looks like this:

Languages

id
name // for example: English
short_name // for exmaple: en

Dictionary

id
key
value
language_id

and my models looks like this:

Language Model

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Language extends Model
{
    use SoftDeletes;
    protected $softDelete = true;
    protected $dates = ['deleted_at'];

    public function dictionary()
    {
        return $this->hasMany('App\Dictionary');
    }
}

Dictionary Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Dictionary extends Model
{
    protected $table = 'dictionary';

    public function language()
    {
        return $this->belongsTo('App\Language');
    }

}

thank you for your help!

!!!UPDATE!!!

i added 1 more table called

Labels

id
label_name

and change the dictionary table to:

Dictionary

id
lable_id
value
language_id

how can i make this work so i can pull the label_name instead of the label_id

$lables = Dictionary::whereHas('language', function($query) {
    $short_name = basename(__DIR__);
    $query->where('short_name', $short_name);
})->pluck('value', 'label_id')->toArray();

回答1:


You can use Laravel's whereHas() function as:

$lables = Dictionary::whereHas('language', function($query) {
    $query->where('short_name', 'en');
})->get();

Update

If you want to get rid of your foreach() then you can use Laravel's pluck() function as:

$lables = Dictionary::whereHas('language', function($query) {
    $query->where('short_name', 'en');
})->pluck('value', 'label')->toArray();



回答2:


I guess it could be something like:

$lables     = Dictionary::with('language')->where('short_name', 'en')->get();


来源:https://stackoverflow.com/questions/40272889/laravel-5-3-eloquent-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!