【渴求式加載】laravel中with()的使用(關聯)

測試了好半天才跑通,記錄下本身的例子,以便查詢使用:php

【Model】原模型 文章表 belongsTo 分類關係表html

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Articles extends Model
{
    protected $table = 'articles';

    public static function getValue($id)
    {
        return self::find($id)->toArray();
    }

    public function a_to_c()
    {
        return $this->hasOne('App\Models\ClassificationArticles', 'article_id', 'id');
    }

    public function a_to_c2()
    {
        return $this->belongsTo('App\Models\ClassificationArticles', 'id', 'article_id');
    }

    public function a_to_c3()
    {
        return $this->hasMany('App\Models\ClassificationArticles', 'article_id', 'id');
    }

    /**
     * 返回側邊欄最新文章列表
     * @return mixed
     */
    public static function getNewList($num)
    {
        return self::select('*') -> join('classification_to_articles', 'classification_to_articles.article_id', '=', 'articles.id') -> orderBy('articles.created_at', 'desc') -> take($num) -> get() -> toArray();
    }

    /**
     * 返回側邊欄隨機推薦文章列表
     * @param $num
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getRandomList($num)
    {
        return self::with('a_to_c2') -> select('*') -> orderBy(DB::raw('RAND()')) -> take($num) -> get();
    }
}

關鍵語句:數組

    public function a_to_c2()
    {
        return $this->belongsTo('App\Models\ClassificationArticles', 'id', 'article_id');
    }


    /**
     * 返回側邊欄隨機推薦文章列表
     * @param $num
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getRandomList($num)
    {
        return self::with('a_to_c2') -> select('*') -> orderBy(DB::raw('RAND()')) -> take($num) -> get();
    }

結果:dom

 

 

 

 之前全toArray()轉成數組,本次使用對象的方式:測試

<?php
    $data_random = App\Models\Articles::getRandomList(8);
?>
<div class="widget">
    <h3>隨機推薦</h3>

    <hr>
    <ul class="hotComments">
        @foreach($data_random as $v)
        <li>
            <div class="hotComments-one-img">
                <a href="/news/{{ $v -> a_to_c -> classification_id }}/{{ $v -> id }}.html" title="{{ $v -> title }}">
                    <img src="{{ $v -> img }}" alt="{{ $v -> title }}">
                </a>
            </div>
            <div class="hotComments-recent-title">
                <h4 class="title"><a href="/index.php?r=article/Content/index&content_id=126" title="{{ $v -> title }}">{{ $v -> title }}</a></h4>

            </div>
        </li>
        @endforeach
    </ul>
</div>

運行結果:ui

 

 

 

相關文章
相關標籤/搜索