Laravel创建简单的RelationShip并从其他表中获取用户数据

时间:2015-11-29 10:51:53

标签: laravel eloquent laravel-5.1

我在UserMerchant两个表格中创建了简单的RelationShip:

class User extends Model implements AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }
    public function merchant()
    {
        return $this->hasMany('App\Merchant');
    }
}
App\Merchant中的

是:

class Merchant
{
    protected $table = 'merchand_web_service';
    protected $fillable = ['agent_unique_id', 'agent_company_name', 'agent_company_logo'];

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

我的迁移文件是:

class MerchandWebService extends Migration
{
    public function up()
    {
        Schema::create('merchand_web_service',function(Blueprint $table){
            $table->increments('id');
            $table->string('customer_key','50');
            $table->string('company_name','50');
            $table->string('company_logo','100');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('merchand_web_service');
    }
}

现在我想通过Controller上的这段代码访问数据库User表上的Merchant数据:

$all_records = Merchant::with('user')->orderBy('id', 'DESC')->paginate(50);

不幸的是我收到了这个错误:

Call to undefined method app\Merchant::with()

1 个答案:

答案 0 :(得分:0)

你错过了这里从基本模型扩展Merchant课程。

应该是:

class Merchant extends Model

而不是

class Merchant

您还应该使用与名称空间完全相同的大小写。查看错误,请使用app\Merchant代替App\Merchant