如何使用Laravel雄辩地让所有客户所有付款交易

时间:2020-10-02 12:27:05

标签: laravel eloquent

我的代码是:

App \ Models \ Client.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
 protected $guarded = ['id'];
 
public function transactions()
 {
        return $this->hasMany('App\Models\Transaction','clients_id');
 }

}

App \ Models \ Transaction.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
 protected $guarded = ['id'];
 
public function clients()
    {
        return $this->belongsTo('App\Models\Client','clients_id');
    }

}

在控制器中我尝试过

use App\Models\Client;
use App\Models\Transaction;

Client::with('transactions')->orderBy('id', 'desc')->get();

但是它没有按预期工作

预先感谢

1 个答案:

答案 0 :(得分:0)

使用以下方式按交易顺序按顺序排列所有客户

$clients = Client::with('transactions')->orderBy('id', 'desc')->get(); 

返回所有具有1个或多个事务的客户。根据您在上述评论中提到的内容,“尽管交易记录为零,它仍返回所有客户”

$clients = Client::has('transactions')->orderBy('id', 'desc')->get();

$clients = Client::has('transactions', '>=', 0)->orderBy('id', 'desc')->get(); // you can add any number in place of zero 

所有内容都在docs

中给出