简体   繁体   English

Laravel 关系 HasMany

[英]Laravel relationship HasMany

I keep multiple address records belonging to a user.我保留了属于一个用户的多个地址记录。 but when i write with dd i can't access other table's data.但是当我用 dd 写入时,我无法访问其他表的数据。

Following my code:按照我的代码:

user Table user

id |    name       | country |
--- --------------  ----------   

7  | Mr. Lenny Bins| Belgium
2  | Dalton Miller | Swaziland

address Table address

user_id | address         
-------- ---------
7       | 740 Brown Greens Suite  
7       | 9906 Cleora Wall Apt.      
2       | 53977 Kip Center Apt

UserModel

 public function getAddress()
    {
        return $this->hasMany(Address::class);
    }

UserController

$users = User::where('id' ,7)->with('getAddress')->get();

dd($users->toArray());
// The output of this is below

这个的输出

dd($users->getAddress->toArray());

I get an error when I try like this.当我这样尝试时出现错误。

Property [getAddress] does not exist on this collection instance.此集合实例上不存在属性 [getAddress]。

Firstly you are using get that will return collection, In Following you will get all users with their addresses.首先,您使用 get 返回集合,在 Following 中,您将获得所有用户及其地址。

$users = User::where('id',7)->with('getAddress')->get();

You can use first() instead of get() as you are finding only one user您可以使用first()而不是get()因为您只找到一个用户

$user = User::where('id' ,7)->with('getAddress')->first();

If You want only address of that user use如果您只想使用该用户的地址

dd($user->getAddress)

Or If you want only in form of array use或者如果你只想以数组形式使用

dd($user->getAddress->toArray())

User Model用户 Model

public function getAddress()
{
  return $this->hasMany('App\Address');
}

Get User(s)获取用户

$users = \App\User::with('getAddress')->where('id' ,7)->get();

Iterate and read data迭代和读取数据

foreach ($users as $user) {
  echo '<pre>' , var_dump($user->getAddress()->first()['address']) , '</pre>';
}

$users = User::with('getAddress')->where('id',7)->first(); $users = User::with('getAddress')->where('id',7)->first();

dd($users); dd($用户);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM