Laravel 5.5
I've got two models, User and Conversation
User to Conversations is a many to many relationship (both ways).
My table structure is as follows:
conversation is on database_1
conversation_user is on database_1
user is on database_2
Inside App\Conversation.php:
protected $connection = 'database_1';
protected $table = 'conversations';
public function users()
{
return $this->belongsToMany("App\User");
}
Inside App\User.php:
protected $connection = 'database_2';
protected $table = 'users';
public function conversations()
{
return $this->belongsToMany("App\Conversation");
}
All of this is on the same server but is there a way to have this working or not ?
When querying the relationship on Conversation to get users, it's looking for database_2.conversation_user instead of database_1.conversation_user
So in essence, I need to say that the Pivot table is located in database_1, is there a way to do this?
One way to work around this is using the query builder to create the relationship. In your User model try:
public function conversations()
{
return DB::connection('db1_connection_name')->table('conversation_user')->where('user_id', $this->id)->get();
}
Apparently you can prefix the connection in a relationship also:
public function conversations() {
return $this->belongsToMany(User::class, env('DB_CONNECTION_1').'.conversation_user', 'user_id', 'conversation_id');
}
Related
Have researched extensively eloquent relationships and laravel all afternoon and can't seem to find a solution.
I have a transaction table displaying User IDs in the From and To columns. I want to show the users emails that correspond to their IDs.
Here is my relationships:
Transaction model:
public function user()
{
return $this->belongsTo('App\User', 'id', 'email');
}
User model:
public function transaction()
{
return $this->hasMany(App\Transaction);
}
And heres the code from the controller. However I KNOW this just returns ALL the transactions. But I really can't find how I would display the emails instead of the IDs:
public function index()
{
$table = Table::create(Transaction::get());
return view('table', compact('table'));
}
Maybe you should try to get transactions with related model (user) or with join to users table?
$transactions = Transaction::query()->with(['user'])->get();
$table = Table::create(Transaction::get());
$table->addColumn('email', 'E-mail', function($model) {
return $model->user->email;
});
return view('table', compact('table'));
I have two MSSQL tables so i created two models [Adress] and [Webshop]. The foreign key is Adresse in both tables.
1.Model [Adress]
class Adress extends Model
{
protected $table = "Adress";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function webshop()
{
return $this->hasOne('App\Webshop', 'Adresse');
}
}
2.Model [WebShop]
class Webshop extends Model
{
protected $table = "Webshop";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function adress()
{
return $this->belongsTo('App\Adress','Adresse');
}
}
I would like to make a table with some data from the first and second table like the webshopID, mobile is in [Webshop] table and adress in the [Adress] table. I think this is a one to one relationship between this two tables.
in php artisan tinker:
App\Adress::all(); -> this is working
App\Adress::find(2910)->webshop -> this is also working
App\Adress::with('webshop')->get() -> this is NOT working
I would like to retrieve data from this two tables at the same time. Is this possible with a relationship or do i heave to use the joins?
EDIT:
maybe my foreignKeys are wrong
Adress table:
Webshop table:
Please try with this -
use App\Adress;
use App\Webshop;
$result = Webshop::with('Adress')->where('Webshop.id',$id)->get();
or
$result = Adress::with('Webshop')->where('Adress.id',$id)->get();
Hope this will help you.
Try to change your relationship in Address model to
$this->hasOne('App\Webshop', 'Adresse', 'Adresse');
and in Webshop model
$this->belongsTo('App\Address', 'Adresse', 'Adresse');
EDIT
Now to retrieve the relationships you can do
$webshop = App\Address::find($id)->webshop;
$address = App\Webshop::find($id)->address
I've got Tag and Attendee Eloquent models, they are in many-to-many relation. Pivot table has also two more attributes – value_int and value_string. My Attendee model looks like this:
class Attendee extends Model
{
public $timestamps = false;
protected $fillable = [
'event_id'
];
public function tags() {
return $this->belongsToMany('App\Models\Tag', 'attendee_tag', 'attendee_id', 'tag_id')
->withPivot(['value_string', 'value_int']);
}
public function scoreTagValue($tag_id) {
return $this->tags->where('tag_id', '=', $tag_id)->first();
}
}
What I want is to obtain pivot values based on Attendee model and variable tag_id, so I've written scoreTagValue function, but it always returns null and I don't know why :( I'm calling it this way:
$attendee->scoreTagValue($tag_id). Thanks for your help :)
You need to access the relation, not the property:
public function scoreTagValue($tag_id) {
return $this->tags()->where('tag_id', '=', $tag_id)->first();
}
Also, according to the docs, withPivot() does not take an array, so:
->withPivot('value_string', 'value_int');
I have query bulider's query like this
$schedule = DB::table('users')
->join('tblHomeCourts','users.homeCourtId','tblHomeCourts.homeCourtId')
->join('tblUserHomeCourts','tblUserHomeCourts.userId','users.userId')
->join('tblSchedules','tblUserHomeCourts.userHomeCourtId','tblSchedules.userHomeCourtId')
->select('tblHomeCourts.homeCourtName', 'tblHomeCourts.address','tblSchedules.timeFrom','tblSchedules.timeTo','tblSchedules.duration','tblSchedules.scheduleStatus','users.firstName','users.lastName','users.profilePic','users.userId')
->where(['tblSchedules.scheduleStatus'=> 0,
])->where('timeFrom','>',$request->currentTime)
->where('timeTo','>',$request->currentTime)
->where('tblUserHomeCourts.homeCourtId',$homeCourtId)
->get();
Now, I want to convert this into proper eloquent query using eloquent relationship I'm fully messed up with relationships can somebody please help me to find out the solution?
thanks :)
To achieve this we have to define relationships among the related table for the first place. Then we need to load the joint table using the with method.
For example you User model should look like this:
class User extends Model{
protected $table = 'users';
public function homeCourt(){
//Many to one relation between user and homeCourt
return $this->belongsTo(HomeCourt::class, 'homeCourtId', 'homeCourtId');
}
public function userHomeCourts(){
//One to many relation between user nad userHomeCourt
return $this->hasMany(UserHomeCourts::class, 'userId', 'userId');
}
}
Your HomeCourt model should look like:
public class HomeCourt extends Model{
protected $table = 'tblHomeCourts';
public function user(){
//One to many relation between homeCourt and user
return $this->hasMany(User::class, 'homeCourtId', 'homeCourtId');
}
}
Your UserHomeCourt model should look like:
public class UserHomeCourt extends Model{
protected $table = 'tblUserHomeCourts'
public function user(){
//Many to one relation between userHomeCourts and users
return $this->belongsTo(User::class, 'userId', 'userId');
}
public function schedules(){
//One to many relation between userHomeCourts and schedule
return $this->hasMany(Schedule::class, 'userHomeCourtId', 'userHomeCourtId');
}
}
Your Schedule model should look like:
public function Schedule extends Model{
protected $table = 'tblSchedules';
public function userHomeCourt(){
//Many to one relation between schedule and userHomeCourts
return $this->belongsTo(UserHomeCourt::class, 'userHomeCourtId', 'userHomeCourtId');
}
}
Now you are ready to build your query. This query is bit different than the query you have built using query builder. Besides, the output of laravel eloquent query is also different. You have to adjust that result with you view:
You can query like this:
$users = User::with('homeCourt', 'userHomeCourts.schedule')->where('timeTo', '>', ,$request->currentTime)->get();
This query is just an example, you have to define it according to your requirement. Here, the parameters of with methods are the methods name of that users table relation with other tables. This is how it works.
You can read more here: https://laravel.com/docs/5.4/eloquent-relationships
I have below query in core php:
SELECT DISTINCT device_tocken FROM push_details JOIN users ON users.id=push_details.user_id
I have to integrate it in laravel 4
Application already have User extends Eloquent class
I created Push_details class as below
class Push_details extends Eloquent {
public $table = 'push_details';
public function User() {
return $this->hasMany('\User','id');
}
}
Table : users
Primary key : id
Table: push_details
Primary key: id
Foreign key: user_id belongsTo('users.id');
But i m not able to get expected result.
One more thing i didn't write anything in User's model yet.
Only way to join table is.. to join it, as Eloquent relations don't work using joins but separate queries with WHERE IN clauses. So this will do:
DB::table('push_details')
->select('device_tocken')
->distinct()
->join('users','users.id','=','push_details.user_id')
->get();
Above will return array of stdObject's so or if you need Eloquent Collection with Eloquent models as a result replace DB::table('push_details')->select... with PushDetails::select...
Now, correct your relations, as they are wrong:
// PushDetails model (as previously stated, I suggest renaming it to StudlyCase)
public function user() {
return $this->belongsTo('\User','user_id'); // user_id is may be omitted here
}
// User model
public function pushDetails() {
return $this->hasMany('\PushDetails','user_id'); // user_id is may be omitted here as well
}
In your User model, you need to link back to the PushDetails model, like so
class User extends Eloquent {
public function push_details() {
return $this->belongsTo('PushDetails');
}
}
Use CamelCase for Class names, because laravel has several functions, in which CamelCase are changed to snake_case
Change
public function User() {
return $this->hasMany('\User','id');
}
to
public function users() {
return $this->hasMany('User');
}
See the docs 'Eloquent ORM' for more...