从模型中获取最新的对象 - laravel雄辩

时间:2016-11-15 08:09:56

标签: laravel model eloquent relationship laravel-5.3

我有两个模型:SupplierQuotation。我可以使用foreach列出供应商的所有报价:

// in my `Supplier` model:
public function quotations()
{
        return $this->hasMany('App\Models\Quotation', 'supplier_id');
}

现在我想只打印最近的报价。我能想到的最好的是模型中的这个函数:

public function newestQuotation()
{
    return $this->hasMany('App\Models\Quotation', 'supplier_id')->orderBy('offered_at','desc')->limit(1);
}

和这个foreach循环:

@foreach($o->newestQuotation as $q)
     @include('displaymodules.module_quotations_mini', array('bg_color' => 'bg-danger'))
@endforeach

待办事项:

上面的代码完成了这项工作......但是如何才能正确完成?我正在考虑做一个帮手,但在我的模型中执行这个功能似乎更像是一个好习惯。

谢谢

编辑:

也许我还不够清楚......我不想用foreach来访问这个对象。 我想要的是这样的片段:

@include('displaymodules.module_quotations_mini', array( 'q' => $o->latestQuotations))

当查询具有->first()时,我得到这样的对象,但是当它具有' - > get()`时,我得到这样的对象。 当我做的时候

$ latestQuotation = App \ Models \ Quotation:where(' supplier_id',3) - > orderBy(' offers_at,' desc') - > first( );

为了得到我想要的东西而没有foreach我使用这个临时解决方案

<?php 
$latestQuotation = App\Models\Quotation::where('supplier_id', $o->id)->orderBy('offered_at', 'desc')->first(); 

?>
@if(isset($latestQuotation))
    @include('displaymodules.module_quotations_mini', array('bg_color' => 'csch_subtle_3', 'q' => $latestQuotation))
@endif

尝试实施Krishan Koenig的回答

尝试#1

<?php $latestQuotations = $o->latestQuotations(); ?>

{{print_r($latestQuotations)}}

结果:domain.dev当前无法处理此请求。 HTTP ERROR 500

尝试#2

{{$o->latestQuotations()->offered_at}}

{{$o->latestQuotations->offered_at}}

结果: Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$offered_at (View:\resources\views\leads\_show_bestoffers.blade.php) (View: \resources\views\leads\_show_bestoffers.blade.php)

尝试#3 - 我想要的解决方案

@include(&#39; displaymodules.module_quotations_mini&#39;,数组(&#39; bg_c​​olor&#39; =&gt;&#39; csch_subtle_5&#39;,&#39; q&#39; =&gt; $邻 - &GT; latestQuotations))

结果: Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$offered_at (View:\resources\views\leads\_show_bestoffers.blade.php) (View: \resources\views\leads\_show_bestoffers.blade.php)

5 个答案:

答案 0 :(得分:0)

您可以在相关模型中创建一个新范围,将其称为最新版本:

public function scopeLatest($query)
{
    return $query->orderBy('offered_at','desc')->limit(1);
}

然后在你的关系中:

public function newestQuotation()
{
   return $this->hasMany('App\Models\Quotation', 'supplier_id')->latest();
}

答案 1 :(得分:0)

您可以在Supplier模型中创建新的关系:

public function newestQuotation()
{
    return $this->hasOne('App\Models\Quotation', 'supplier_id')->orderBy('offered_at', 'desc');
}

然后您可以将其查询为:

$supplieres = Supplier::with('newestQuotation')->take(20)->get();

@foreach ($supplieres as $supplier)
  {{ $supplier->newestQuotation->title }} // just an example
@endforeach

<强>更新

尝试将您的查询视为:

$supplier = Supplier::where('id', $id)->first();

$latestQuotation = $supplier->newestQuotation;

答案 2 :(得分:0)

例如:

Quotation.php模型

class Quotation extends Model
    {
        protected $primaryKey = 'id';

        function withSupplier() {
       return $this->hasMany('App\Models\Quotation', 'id', 'supplier_id')->orderBy('offered_at','desc');
    }

    public function newestQuotation($supplier_id){
         News::with('withSupplier')->where('supplier_id', $supplier_id)->get();
    }
}

在控制者中:

public function pageQuotations(Quotation $quotation)
    {
        $quotations = $quotation->newestQuotation(1); //id Supplier
        return view('displaymodules.quotations', $quotations);
    }
引号.blade.php中的

(示例)

<table>
<tbody>
@foreach ($quotations as $quotation)
<tr>
<th>{{ $quotation->title }}</th>
<td>{{ $quotation->withSupplier()->title }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>

答案 3 :(得分:0)

创建范围并使用现有关系!

public function quotations()
{
    return $this->hasMany('App\Models\Quotation', 'supplier_id');
}


public function scopeLatest($query)
{
    return $query->orderBy('offered_at','desc')->limit(1);
}

public function latestQuotations()
{
    return $this->quotations()->latest();
}

在您的控制器中,您可以使用

查询它们
//...
$latestQuotations = $supplier->latestQuotations();

已修改版本

// supplier model
public function quotations()
{
    return $this->hasMany(Quotation::class);
}

public function scopeLatest($query)
{
    return $query->orderBy('offered_at','desc');
}

public function latestQuotations()
{
    return $this->quotations()->latest()->get();
}

// web route
Route::get('/', function () {
    $latestQuotations = App\Supplier::first()->latestQuotations();
    return view('welcome', compact('latestQuotations'));
});

// welcome view
{{ $latestQuotations }}

......为我工作。

答案 4 :(得分:0)

最简单的解决方案是

W/System.err: org.json.JSONException: No value for address W/System.err: at org.json.JSONObject.get(JSONObject.java:355) W/System.err: at org.json.JSONObject.getString(JSONObject.java:515) W/System.err: at com.example.amr.fujeraapp.News.SingleNewsDetails$1.onResponse(SingleNewsDetails.java:64) W/System.err: at com.example.amr.fujeraapp.News.SingleNewsDetails$1.onResponse(SingleNewsDetails.java:56) W/System.err: at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72) W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) W/System.err: at android.os.Handler.handleCallback(Handler.java:808) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:103) W/System.err: at android.os.Looper.loop(Looper.java:193) W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5333) W/System.err: at java.lang.reflect.Method.invokeNative(Native Method) W/System.err: at java.lang.reflect.Method.invoke(Method.java:515) W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828) W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644) W/System.err: at dalvik.system.NativeStart.main(Native Method)

然后,对于集合的计数,结果是单个对象。 这允许使用$entity = $collection->first();$entity->id等字词。