簡體   English   中英

如何將數據獲取到 Eloquent 中具有許多關系的表

[英]How to get data to table that has many relationships in Eloquent

我正在嘗試處理 eloquent model Post ,它有兩個 hasOne 關系: offer_postrequest_post

Post.php

class Post extends Model
{
    use HasFactory;

    protected $table = 'tbl_post';
    protected $fillable = ['email', 'postIdentity', 'postStatus'];

    public $timestamps = false;
    public $primaryKey = 'indexPost';

    public static function boot()
    {
    parent::boot();
    self::creating(function ($model) {
        $model->postNumber = (string) Uuid::generate(4);
    });
    }

    public function pasabuy_user() {
        $this->belongsTo(PasabuyUser::class, 'email', 'email');
    }

    public function offer_post() {
        return $this->hasOne(OfferPost::class, 'postNumber', 'postNumber');
    }

    public function request_post() {
        return $this->hasOne(RequestPost::class, 'postNumber', 'postNumber');
    }
}

OfferPost.php

class OfferPost extends Model
{
    use HasFactory;

    protected $table = 'tbl_shoppingOfferPost';
    protected $fillable = ['postNumber', 'postStatus', 'deliveryArea', 'shoppingPlace', 'deliverySchedule', 'transportMode', 'capacity', 'paymentMethod', 'caption'];

    public $timestamps = false;
    public $primaryKey = 'indexShoppingOfferPost';

    public function post() {
        return $this->belongsTo(Post::class, 'postNumber', 'postNumber');
    }
}

RequestPost.php

class RequestPost extends Model
{
    use HasFactory;

    protected $table = 'tbl_orderRequestPost';
    protected $fillable = [
        'postNumber',
        'postStatus',
        'deliveryAddress',
        'shoppingPlace',
        'deliverySchedule',
        'paymentMethod',
        'shoppingList',
        'caption'
    ];

    public $timestamps = false;
    public $primaryKey = 'indexOrderRequestPost';

    /**
     *    [post description]
     *    @author Al Vincent Musa
     *    @return [type] [description]
     */
    public function post() {
        return $this->belongsTo(Post::class, 'postNUmber', 'postNumber');       
    }
}

這就是我的桌子的樣子。 在此處輸入圖像描述

現在我想獲得所有帖子(提供帖子和請求帖子)

SELECT from tbl_post INNER JOIN tbl_shoppingOfferPost ON tbl_post.postNumber = tbl_shoppingOfferPost.postNumber

同樣對於請求帖子。

我來了

$post = Post::has('offer_post')->get();

但這僅返回來自 tbl_post 的數據。 但同時需要 tbl_post 和 tbl_shoppingOfferPost。 我很難理解文檔。 我不知道從哪里開始。 任何幫助深表感謝。 我只需要一個指針在哪里看。 謝謝

你可以這樣做

$post::with(['offer_post','request_post'])->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM