HowApped
HowApped

Reputation: 1021

Eloquent ORM relationships one-to-one or one-to-many?

I see the power of using Eloquent but have yet to put it to good use in my project. With two tables I want to achieve this:

//output - LinkedIn
echo User::find(42)->SocialProvider->Name

I have a user table and I have a SocialProvider table with a list of social sites with their name and api key info.

Record 42 in my user's table has a column 'SocialProviderID' with the the id of the LinkedIn record in my SocialProvider table.

I have defined the relationships in model classes as following

class User extends BaseModel implements UserInterface, RemindableInterface {

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'dbo_RegisteredUser';
    protected $primaryKey = "UserID";

    public function SocialProvider() { return $this->hasOne('SocialProvider','id'); }

AND

class SocialProvider extends Eloquent  {

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'dbo_SocialProvider';

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

But the queries and results are not executing as I'd like.

Does anyone have an ideas?

I'm using MSSQL but in my more familiar MYSQL, I would like this ORM scenario to perform a join like this:

SELECT * FROM dbo_RegisteredUser
LEFT JOIN (dbo_SocialProvider)
             ON (dboRegisteredUser.SocialProviderID=dbo_SocialProvider.id)
WHERE dbo_RegisteredUser.UserID=42

Thanks

Jon.

Upvotes: 1

Views: 1062

Answers (2)

HowApped
HowApped

Reputation: 1021

Ahh I figured it out with a bit of debugging. I specified the relationships incorrectly.

In my User model I needed

class User extends Eloquent implements UserInterface, RemindableInterface {

    public function socialProvider() { 
        return $this->belongsTo('SocialProvider','SocialProviderID'); 
     }

Upvotes: 1

Kylie
Kylie

Reputation: 11749

Well...relationships use the ID of the model in question....and you're not referencing the actual user anywhere...

You need to have a collumn in the social Provider table that stores the user_id

Then in your functions...

public function SocialProvider() { return $this->hasOne('SocialProvider','user_id'); }

and...

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

Upvotes: 0

Related Questions