douzhankui0758 2016-10-26 22:07
浏览 40
已采纳

Laravel 5.3雄辩的关系

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();
  • 写回答

2条回答 默认 最新

  • dpntq48842 2016-10-27 01:41
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?