简体   繁体   中英

Laravel 4 - one-to-many relationship returns null

I'm upgrading from L3. One customer has many users, and users belong to customers.

Migrations:

Schema::create('customers', function($table)
{
 $table->increments('id');
 $table->string('name')->unique();
 $table->index('name');
 $table->string('full_name');
 $table->string('driver');
 $table->string('host');
 $table->string('database');
 $table->string('username');
 $table->string('password');
 $table->timestamps();
});

Schema::create('users', function($table)
{
 $table->increments('id');
 $table->string('email')->unique();
 $table->index('email');
 $table->integer('customer_id')->unsigned();
 $table->foreign('customer_id')->references('id')->on('customers')->on_update('cascade')->on_delete('cascade');
 $table->integer('domain_id')->unsigned();
 $table->foreign('domain_id')->references('id')->on('domains')->on_update('cascade')->on_delete('cascade');
 $table->string('password');
 $table->string('name');
 $table->string('state');
 $table->string('verification_token');
 $table->string('resend_verification_token');
 $table->string('change_password_token');
 $table->string('last_ip');
 $table->timestamp('last_login');
 $table->timestamp('verification_timestamp');
 $table->timestamp('change_password_timestamp');            
 $table->timestamps();
});

Models:

class Customer extends Eloquent {
  public function users()
  {
     return $this->hasMany('User');
  }
}

class User extends Eloquent {
  public function customer()
  {
     return $this->belongsTo('Customer');
  }
}

But trying this relationship as follows:

$user = User::find(1);
echo $user->customer->name;

throws an exception ( "Trying to get property of non-object" ) because customer is null.

And trying:

$user = User::find(1)->customer();

throws the exception ( Call to undefined method Illuminate\\Database\\Query\\Builder::customer() ).

What am I doing wrong?

I had renamed the User model that ships with Laravel to User_.php, and replaced it with my own.

Seems that somehow the replacement model wasn't getting called. Everything worked once I removed the original user model completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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