如何通过laravel雄辩的模型连接两个表

时间:2019-05-17 11:08:38

标签: php eloquent

我有两个表,一个是csps,另一个是事务,它具有laravel模型。我想通过laravel雄辩的模型加入他们。我不想这样使用DB::csps

csps表

'ko_id', 
'ko_name', 
'account_number'

交易表

'transaction_date_time', 
'limit_conf_by', 
'ko_id', 
'opening_limit', 
'amount', 
'closing_limit', 
'is_cheque_issued', 
'lot_id', 
'lot_amount',
'deposite_account',
'lot_date',

我想显示带有csps详细信息的交易详细信息。我知道如何加入数据库,但我想通过laravel雄辩的模型进行展示。我不知道如何加入模型。

我尝试过

这是交易模式

namespace App;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    protected $table = 'transactions';
    public $timestamps = false;

    // protected $attributes = [
    //     'delayed' => false,
    // ];

    protected $fillable = [
        'transaction_date_time', 'limit_conf_by', 'ko_id', 'opening_limit', 'amount', 'closing_limit', 'is_cheque_issued', 'lot_id', 'lot_amount','deposite_account','lot_date',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    // protected $hidden = [
    //     'password', 'remember_token',
    // ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'transaction_date_time' => 'datetime',
    ];

    public function csp(){
        return $this->belongsTo('App\Csp');
    }
 }

这是csp模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Csp extends Model
{
    use SoftDeletes;

    protected $table = 'csps';
    protected $primaryKey = 'ko_id';
    public $incrementing = false;
    public $timestamps = false;

    protected $fillable = [
        'ko_id', 'ko_name', 'account_number'
    ];
    public function transaction(){
        return $this->hasMany('App\Transaction');
    }

}

1 个答案:

答案 0 :(得分:0)

凭借Laravel的雄辩,这非常简单。您无需显式编写联接命令。您可以利用Laravel的动态属性。

请参见Laravel Docs

代码应为:

<?php

$transaction = Transaction::find(20); // assuming 20 is one of the IDs in your database
$csp_details = $transaction->csp;
dd($csp_details); // you would get your csp details here for rows.