【问题标题】:Laravel get whole database table with its associatesLaravel 获取整个数据库表及其关联
【发布时间】:2021-07-06 02:15:26
【问题描述】:

是否有可能获取整个数据库的表及其关联?

我的例子

class Gambler extends Model
{
    use HasFactory;

    public function horse()
    {
        return $this->belongsTo(Horse::class, 'horse_id', 'id');
    }
}

我正在使用 axios 获取 Gamblers 的数据,这些数据在控制器中与此代码一起返回

public function getGamblers () {
        echo Gambler::all();
    }

但是我也想获得所有相关的马匹。我可以像这样轻松搞定一个

    public function getGamblers () {
        echo Gambler::find(1)->horse;
    }

但也许有可能做这样的事情,在我的情况下这是行不通的

    public function getGamblers () {
        echo Gambler::all()->horse;
    }

【问题讨论】:

    标签: php database laravel


    【解决方案1】:

    您应该在控制器中使用return,而不是echo

    因为您使用的是axios,所以JsonResponse 会更合适:

    public function getGamblers () {
       return response()->json(Gambler::all(), 200);
    }
    

    Gambler::all() 将返回 CollectionGambler

    在前端,循环遍历从 Laravel 获得的数据:

    let gamblers = [];
    
    axios.get('/your-get-gamblers-url')
      .then(function (response) {
        gamblers = response.data;
      })
    
    gamblers.forEach(gambler => console.log(gambler))
    

    如果出于某种原因您需要在 php 中对每个 Gambler 做一些事情,您可以像这样遍历集合:

    $gamblers = Gambler::all()
    foreach($gamblers as $gambler) {
        //$gambler->horse
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多