detach single belongsToMany relationship - eloquent

I need to detach a single belongs to many relationship however I can't figure it out. Below is how I have got the belongsToMany relationship setup:
WebsiteController
/** #var User $user */
$user = \Auth::user();
$favorites = $user->favoriteWebsites;
User
/**
* #return BelongsToMany
*/
public function favoriteWebsites(): BelongsToMany
{
return $this->belongsToMany(Website::class, 'planner_favorite_websites');
}
When a user clicks a button I will have access to the website ID associated with the pivot table. Tables are setup like follows:
websites
id, name, code
users
id, fname, lname
planner_favorite_websites
id, user_id, website_id
How can I use the website ID to detach just that single website from the current user logged in. So I will have the Website ID and User ID.
Obviously I could do a simple where(['website_id' => 0, 'user_id' => 0]) but this doesn't seem the correct way to use relationships.

Related

How to update referenced key id to null in one to one doctrine

I am running in this issue. Whenever I delete a company entity, the contact entity which has company's id as reference key throws an error.
Company for IDs ID(29) was not found
I have this:
Contacts Table
ID, Name, Company_ID
Companies Table
ID, Name
And I have these relationships in their entities.
Contact.php
/**
* #ORM\OneToOne(targetEntity="Company", cascade={"persist"})
* #ORM\JoinColumn(name="Company_ID", referencedColumnName="ID")
*/
private $company;
Company.php
/**
* #ORM\OneToMany(targetEntity="Contact", mappedBy="company")
* #ORM\JoinColumn(name="ID", referencedColumnName="Company_ID")
*/
private $contacts;
I'm fairly new to doctrine. But when I delete a company of ID 1 then all the contacts with Company_ID = 1 should become null. Is this something that doctrine could handle or I MUST write manual code for it.

Laravel: When creating a record with relations, cannot insert foreign key into table

I am following this exercise of an "intermediate task list" from Laravel 5.2 documentations and have some difficulty understanding how this piece of code works.
$request->user()->tasks()->create([
'name' => $request->name,
]);
Question 1
Specifically, I am confused at the relation between the user() and tasks() methods. Why and how exactly can we make the user() and tasks() methods available from the $request object?
Question 2
I created a similar app and has Person and Country models. I want to pass the country_id input from a dropdown list, but I can't get the database updated, using the following code.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'country_id' => 'required|max:3',
]);
$request->user()->people()->create([
'name' => $request->name,
'country_id' => $request->country_id,
]);
return redirect('/people');
}
Why is it that the country_id cannot be saved to the table? I tried changing the user() to country() but the error message says, "class Country" was not found. But why is the 'user()' in the tutorial available then? I am baffled.
The user() method of request is available if the user making the request is authenticated.
Since it uses User model it can also fetch the related model. For tasks() to work Task relationship must be defined in user model.
For country_id to be created(mass assigned) ensure its included in $fillable property of the People model
$fillable = ['country_id']
Please read Eloquent model relationship section in Laravel documentation.

required field for other model's field in yii

I need to store a record in First Model. It has around 10 fields. Now, I need to apply required rule for one field which i'm storing in SECOND model and I'm getting these values for this field from Third model.(it is a drop down field)
how can i make this field mandatory in yii??
can any one help please..
Many Thanks,
You can add additional attributes and rules to a model. You don't have to only use attributes that directly relate to fields in your database table. Let's look at a basic example. You have a user (User) table which has the following fields:
id
email
password
And you have another table which stores user profile (UserProfile) information which has the structure:
id
user_id
country
When the user creates their account, you would have a form that captures their information. Your User model would have rules like:
array('email, password', 'required'),
array('email', 'unique', 'message'=>'Email already in use'),
...
You can add an attribute for country to your User model like so:
class User extends CActiveRecord {
public $country;
...
And then in your rules you can add the new attribute:
array('email, password, country', 'required'),
array('email', 'unique', 'message'=>'Email already in use'),
...
The country attribute will now be a part of your User model. You can now add that to your form:
<?php echo $form->dropDownList($model,'country',CHtml::listData(Country::model()->findAll(),'id','country_name'),array('empty'=>'-- select a country --')); ?>
Now on your form submit, the $model->validate() method will validate the country field. You can save this manually to your second model (UserProfile), something like:
if(isset($_POST['User'])){
if ($model->validate()){
$user_profile = new UserProfile;
$user_profile->user_id = $model->id;
$user_profile->country = $model->country;
$user_profile->save();
...
Hopefully that answers your question.

Many-to-Many Inserts with Entity Framework

Say I have two entities with about 20 properties per entity and a Many-to-Many relationship like so:
User (Id int,Name string, .......)
Issue (Id int,Name string, .......)
IssueAssignment (UserId,RoleId)
I want to create a new Issue and assign it to a number of existing Users. If I have code like so:
foreach(var userId in existingUserIds)
{
int id = userId
var user = _db.Users.First(r => r.Id == id);
issue.AssignedUsers.add(user);
}
_db.Users.AddObject(user);
_db.SaveChanges();
I noticed it seems terrribly inefficient when I run it against my SQL Database. If I look at
the SQL Profiler it's doing the following:
SELECT TOP(1) * FROM User WHERE UserId = userId
SELECT * FROM IssueAssignment ON User.Id = userId
INSERT INTO User ....
INSERT INTO IssueAssignment
My questions are:
(a) why do (1) and (2) have to happen at all?
(b) Both (1) and (2) bring back all fields do I need to do a object projection to limit the
fields, seems like unnecessary work too.
Thanks for the help
I have some possible clues for you:
This is how EF behaves. _db.Users is actaully a query and calling First on the query means executing the query in database.
I guess you are using EFv4 with T4 template and lazy loading is turned on. T4 templates create 'clever' objects which are able to fixup their navigation properties so once you add a User to an Issue it internally triggers fixup and tries to add the Issue to the User as well. This in turns triggers lazy loading of all issues related to the user.
So the trick is using dummy objects instead of real user. You know the id and you only want to create realtion between new issue and existing user. Try this (works with EFv4+ and POCOs):
foreach(var userId in existingUserIds)
{
var user = new User { Id = userId };
var _db.Users.Attach(user); // User with this Id mustn't be already loaded
issue.AssignedUsers.Add(user);
}
context.Issues.AddObject(issue);
context.SaveChanges();

Why is this Exception?- The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

I m getting this Exception-"The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."
I ve user table and country table. The countryid is referred in user table.
I am getting the above Exception when I am trying to add entry in user table.
This is my code-
using (MyContext _db = new MyContext ())
{
User user = User .CreateUser(0, Name, address, city, 0, 0, email, zip);
Country country = _db.Country.Where("it.Id=#Id", new ObjectParameter("Id",countryId)).First();
user.Country = country;
State state = _db.State.Where("it.Id=#Id", new ObjectParameter("Id", stateId)).First();
user.State = state;
_db.AddToUser(user );//Here I am getting that Exception
_db.SaveChanges();
}
Try adding the user first, then adding the relationships.
See http://www.code-magazine.com/article.aspx?quickid=0907071&page=4
Or, don't use User.CreateUser where you are explicitly setting an Id = 0, instead use User user = new User() {Name = Name, Address = ...}
BTW, with Entity Framework 4 you can set the foreign key IDs directly removing the need to load the related object if you know its ID.