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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用