在laravel 5.4

时间:2017-06-09 12:28:20

标签: php laravel

您好我有以下查询

Deal::with(array('deal_category'=>function($query){
                    $query->select('name as dealcategory');
                }))->get()

当我尝试检索dealcategory时,它不会返回任何值。我在模型中定义了关系,如

交易模型

public function deal_category()
{
    return $this->belongsTo('App\DealCategory', 'deal_category_id', 'id');
}

和交易类别模型一样

public function deals(){
    return $this->hasMany('App\Deal','deal_category_id');
}

任何人都可以帮助我如何获得categoryname?

2 个答案:

答案 0 :(得分:0)

You have to select the primary key to retrieve the necessary results.

Deal::with(array('deal_category'=>function($query){
                $query->select('id', 'name as dealcategory');
            }))->get()

答案 1 :(得分:-2)

Use facade DB. You can try something like this:


    DB::table('deal as d')
    ->join('deal_category as dc', 'd.id', '=', 'dc.deal_id')
    ->select('d.name as dealname', 'dc.categoryname')
    ->get();