簡體   English   中英

如何從 Laravel 6 中的 eloquent 關系返回單列?

[英]How do you return a single column from a eloquent relationship in Laravel 6?

我有 model 'Post',其中包含 'id'、'name'、'content' 和 'status' 列

我有 model 'PostStatus' 有列 'id' 和 'name'

在 Post.php 我有以下內容:

class Post extends Model
{
    public function status()
    {
        return $this->belongsTo('App\PostStatus','status');
    }
}

在其他地方的 controller 中,我有:

Post::with('status')->get()->toArray();

它返回一個數組,其中所有帖子的“id”、“名稱”作為“內容”作為它們的列值,“狀態”作為帖子狀態表中相關行的數據數組。 我想要實現的是“狀態”列只是 PostStatus model 中“名稱”列的字符串值,而不是整行的數組。 我嘗試在 Post model 中的狀態 function 上使用 ->select ,但這仍然將值作為數組返回。 我寧願避免直接使用 SQL 來實現我的目標。

總之,我希望 controller 中的 function 返回:

array(4) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(12) "Post Example"
    ["content"]=>
    string(7) "Content"
    ["status"]=>
    string(6) "Active"
  }

而不是

array(4) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(12) "Post Example"
    ["content"]=>
    string(7) "Content"
    ["status"]=>
    array(2) {
      ["id"]=>
      int(1)
      ["name"]=>
      string(6) "Active"
    }
  }

這並不是關系的真正設計方式,你可能會發現你以后實際上需要這種關系來做其他事情,所以覆蓋它可能不是最好的行動方案。

您應該考慮使用訪問器來返回屬性(例如, $post->status_name )。
https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators

class Post extends Model
{
    // append the attribute for serialization
    $appends = ['status_name'];

    // get an attribute named 'status_name'
    public function getStatusNameAttribute()
    {
        return $this->status->name ?? '';
    }

    public function status()
    {
        return $this->belongsTo('App\PostStatus','status');
    }
}

注意:如果您打算這樣做,明智的做法是在獲取帖子時仍然使用with('status') ,因為它會阻止 Laravel 為每個 label 運行單獨的查詢。 您甚至可能希望在 Post model 的引導方法中將其作為全局 scope 應用,因此您不必每次都這樣做。
https://laravel.com/docs/5.8/eloquent#global-scopes

暫無
暫無

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

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