如何在Laravel中添加多个表关系

时间:2018-07-22 12:08:06

标签: laravel eloquent

我有以下表格,并与Laravel关系建立查询。在我的面板中,一旦用户登录,我将获得用户详细信息和用户业务详细信息,但是现在我也不知道如何获取业务类型详细信息。

用户表:

id | business_id | username | email          | password
1    1             john632    john@gmail.com   *******

用户业务表

id | user_id | business_type_id | business_name
1    1         2                  Fortune

业务类型表

id | business_type_name | description
1    Hotel                Lorem Ipsum
2    Movie                Lorem Ipsum

型号:

用户

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use App\Notifications\ResetPassword as ResetPasswordNotification;
use Laravel\Passport\HasApiTokens;
use Illuminate\Database\Eloquent\SoftDeletes;
use Webpatser\Uuid\Uuid;
use App\RoleUser;
use App\UsersBusiness;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;
    use HasApiTokens;
    use SoftDeletes, EntrustUserTrait {
        SoftDeletes::restore as sfRestore;
        EntrustUserTrait::restore as euRestore;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'business_id', 'username', 'email'
    ];

    public function usersBusiness()
    {
        return $this->belongsTo('App\UsersBusiness', 'business_id', 'id');
    }
}

UsersBusiness

<?php

namespace App;

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

class UsersBusiness extends Model
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tbl_users_business';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'business_type_id', 'business_name'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    /**
     * Dates to be treated as Carbon instances
     *
     * @var array
     */
    public $dates = [
        'deleted_at'
    ];
}

业务类型

<?php

namespace App;

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

class BusinessTypes extends Model
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tbl_master_business_types';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'business_type_name', 'description'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    /**
     * Dates to be treated as Carbon instances
     *
     * @var array
     */
    public $dates = [
        'deleted_at'
    ];
}

代码:

$user = Auth::user();
$data['data'] = $user->load(['usersBusiness'] => function ($query) {
    $query->select(["id", "user_id", "business_name"])->get();
}]);

我得到以下响应数据:

{
    "data": {
        "id": 1,
        "business_id": 1,
        "username": "john632",
        "email": "john632@gmail.com",
        "password": "john632",
        "users_business": {
            "id": 1,
            "user_id": 4,
            "business_type_id": 3,
            "business_name": "Honest"
        },
        "business_types": null
    },
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4YTQ5OTBmOGQxOWQ5NTg1OGFlZWU1MDY0NTBiY2Y2OWJmOWQ3NzFhZjRmN2RmMzBmMWRkZWNmNWY4OTAzM2UyNmI2MzE3MTY3MDMxOTk4In0.eyJhdWQiOiIxIiwianRpIjoiOThhNDk5MGY4ZDE5ZDk1ODU4YWVlZTUwNjQ1MGJjZjY5YmY5ZDc3MWFmNGY3ZGYzMGYxZGRlY2Y1Zjg5MDMzZTI2YjYzMTcxNjcwMzE5OTgiLCJpYXQiOjE1MzIyNjA3ODUsIm5iZiI6MTUzMjI2MDc4NSwiZXhwIjoxNTYzNzk2Nzg1LCJzdWIiOiI1Iiwic2NvcGVzIjpbXX0.f_Xv0SrtTZ9m-40oHjAglCbKv76s_bARQ74XDihhFnI-jtHKwCWiF-jai5Yt6h9QyakCTZEo1bPAJdeph7Bj0_tKJpq3sGvK4t73_LZg_OOcsmAt61a4OSAgI1pjPV0tMMwHCoHm-xLlNnriAyaLCAbTQLQkfrw53467ys6rchE5V0rzy-JswjTfmB6SvZcqXsJQo6CWDRTWYbKvJO0FSmdZfLxxO_u4i_8ah5W63qJ4MSN9q22zkZLQ-L3NZhOux2KkwWiySioL2K25Y_UZmefClYwk1h-EY_LEVht3U7Kpqn9fmM6_Q4ByD-sSzLdAixdbq4REqinSaayzfMY934nijLu7ysEIc0oIukiHYcIk9tGV6DNuQ0CWhqEn0W_308MSBU4Ffyi5SQo7ubb5uPG7l_XOdomIR9dK9KtVONbPe7iF6TuccPCWZwvqKgfFl7TqEgiUWSiAl_ekkiaUDEM3cIuIH8AOLE17UuW4W0VyR2ziIt68au8SEuP2ilMBRsRMsFGbRKQWcvLluNw_qubcdzZ4yX9kuQAvXuBrHAcXb9WMlki2votvd7RKVDwxqwsTJRoeKNtJQdEQRbRZUD6nXyzGkmtEMrfwYoLVgTX3vAgVjO_erYtI5x-NV-EnoLT352odtRDYh5gTzVbmzYAxbLf_XUCDHjvlMEvM81g",
    "status": true,
    "status_code": 1,
    "message": "Login successfully."
}

我也想添加业务类型详细信息,所以请您指导我如何为该表添加关系。

谢谢。

2 个答案:

答案 0 :(得分:1)

像这样在您的UserBusiness模型中创建一个EmiratesTo关系

用户业务模型

public function businessType(){
     return $this->belongsTo(BusinessType::class, 'business_type_id');
}

这样加载后

$user = Auth::user();
$user->load(['usersBusiness.businessType']); //lazy loading
dd($user);

如果仅需要userBusiness及其类型,则

dd($user->usersBusiness);

侧面说明::我认为您在用户表中不需要business_id。只需将user_id保留在userbusiness表中,然后在userBusness的用户模型中添加hasOne(如果用户只能有一个业务)或hasMany(如果用户可以有多个业务)关系。

答案 1 :(得分:0)

我建议您使用API Resources.

例如,对于我来说,我有 ChannelItemResource.php

import re

def count(text, s):
    return len(re.findall(s, text))

print(count('mama ma emu a ema ma mamu', 'ma '))
print(count('mama ma emu a ema ma mamu', 'am'))

ChannelResource.php

4
2

使用此结构,您可以轻松地包含所需的关系,并且结果将以JSON形式出现。

控制器中使用:

public function toArray($request)
    {
        return [
    'id' => $this->id,
    'channel_id' => $this->channel_id,
    'channel' => $this->channel->title,
    'type' => $this->type,
    'description' => $this->description,
    'price' => $this->price,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
];
    }